在 Angular 中将控件动态添加到响应式表单时出现问题

Issue in adding a control dynamically to a reactive form in Angular

我正在研究 Angular 响应式表单。我想动态添加控件以形成。但是当我添加一个控件时,它第一次添加了 两次 我不知道为什么,之后它工作正常。这是代码:

<form [formGroup]="reviewForm" >        
    <span *ngIf="isClicked">              
        <div formArrayName="controlArray">
            <div 
              class="form-group"
              *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">            
              <label>{{label}} </label>                                      
              <input 
                type="{{control.value}}"                       
                class="form-control"                                        
                [formControlName]="i" >                       
            </div>  
        </div>  
    </span>
    <button type="button" (click)="addControl()">Add</button>         
</form>

组件 class 代码,在添加按钮单击事件时调用 addControl():

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {  
  reviewForm: FormGroup;
  inputArray: string[] = [
    'text', 'radio', 'checkbox', 'select', 'textarea', 'button'
  ];

  selectedControl: string = '';   
  isClicked:boolean= false;
  label: string;
  isRequired:boolean = false;
  placeHolderValue: string = "";
  ngOnInit(){
    this.reviewForm = new FormGroup({   
      // 'placeHolder' : new FormControl(null),   
      'controlArray': new FormArray([
        new FormControl(null)
    ])
    });
  }

  addControl(){    
      this.isClicked = true;
      const control = new FormControl(this.selectedControl);
      (<FormArray>this.reviewForm.get('controlArray')).push(control);      
      // console.log(this.selectedControl);      
    }  

  onSubmit(){
    console.log(this.reviewForm);
  }
}

发生的事情非常正常,因为当你的组件创建时,isClicked = false和你的formArray已经包含一个FormControl由于这种情况,开头未显示:<span *ngIf="isClicked">

当您将新控件添加到 FormArray 时,现在它包含两个 FormControl,并且 isClicked 变为 true,两个 formControl 是显示。

这是此行为的原因

希望对您有所帮助:)