如何在Angular中动态添加元素和访问值?

时间:2018-10-17 11:05:12

标签: javascript angular typescript

我正在做一个小项目,允许用户添加动态字段。单击按钮后,我已经能够动态创建输入字段。我正在尝试访问每个字段的值并将其推送到服务。另一方面,另一个组件应该根据用户创建的输入字段的数量来确定div的数量,并且每个div应该根据用户在输入字段中的输入来包含标题。

register.component.html

<h2>Demo App</h2>
<form [formGroup]="myForm">
    <button (click)="addRooms()">Add Room </button>
  <div formArrayName="addRoom">
    <div *ngFor="let r of Rooms.controls; let i=index" [formGroupName]="i">
      <mat-form-field>
        <input matInput placeholder="Enter A Room Name" formControlName="roomName" (keyup)="abc()"/>

      </mat-form-field>
      <button (click)="deleteRoom(i)">Delete</button>
    </div>


  </div>
  <input type="button" (click)="getRoomValues()" value="Get">
</form>

register.component.ts

import { Component, OnInit} from '@angular/core';
import { RegisterModel } from '../models/register.model';
import {FormGroup, FormBuilder, Validators, FormArray, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit, AfterViewInit {
  myForm: FormGroup;
  room: FormGroup;

  constructor(private formBuilder:FormBuilder, private r:Router, private _ele:ElementRef, private _render: Renderer) { }

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      addRoom: this.formBuilder.array([]),
      tst: new FormControl()
    });

  }

  getVal(){
    console.log(this.myForm.value.tst);
  }

  get Rooms(){
    return this.myForm.get('addRoom') as FormArray;
  }


  addRooms(){
    this.room = this.formBuilder.group({
      roomName:new FormControl()
    })

    this.Rooms.push(this.room);
    console.log(this.Rooms);
  }
  abc(){
    console.log(this.room.value.roomName);
  }

  deleteRoom(i){
    this.Rooms.removeAt(i);
  }

  get roomNames(){
    return this.myForm.get('roomNames') as FormArray;
  }
  getRoomValues(){
    console.log(this.myForm.value.addRoom)
  }

1 个答案:

答案 0 :(得分:0)

下面是具有动态添加和删除功能的几个字段的代码示例。

                              <form [formGroup]="linksForm" class="form-horizontal">
                                    <div class="form-group">
                                        <label class="col-md-2 control-label">Links
                                        </label>
                                        <div class="col-md-10">
                                            <div formArrayName="links" *ngFor="let item of linksForm.get('links').controls; let i = index;">
                                                <div [formGroupName]="i">
                                                    <div class="col-md-5">
                                                        <input class="form-control col-md-5" formControlName="name" placeholder="Name">
                                                    </div>
                                                    <div class="col-md-5">
                                                        <input type="url" pattern="https?://.+" placeholder="http://example.com" class="form-control col-md-5"
                                                         formControlName="link">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <button class="btn btn-warning btn-xs m-t-sm" type="button" (click)="removeItem(i)">
                                                            <i name="save" class="fa fa-trash"></i>
                                                        </button>
                                                        <button *ngIf="i == linksForm.get('links').controls.length - 1" class="btn btn-primary btn-xs m-t-sm" type="button" (click)="addItem()">
                                                            <i name="save" class="fa fa-plus"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>

TS:在类中声明以下变量:

linksForm: FormGroup;
links: FormArray;

内部ngOnInit()至少初始化一行:

this.linksForm = new FormGroup({
            'links': new FormArray([this.createItem()])
        });

添加以下用于添加/删除的功能:

addItem(): void {
    this.links = this.linksForm.get('links') as FormArray;
    this.links.push(this.createItem());
  }

   removeItem(index: any) {
      this.links.removeAt(index);

      if (this.links.length == 0) {
         this.addItem();
      }
   }

createItem(): FormGroup {
        return new FormGroup({
            id: new FormControl(),
            name: new FormControl(),
            link: new FormControl(),
            createdAt: new FormControl()
        });
    }