2017-10-18 119 views
0

我正在使用Angular Reactive窗体。我想动态地添加控件来形成。但是当我添加一个控件时,它第一次添加两次我不知道为什么,之后它工作正常。这里是代码:在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> 

组件类代码的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); 
    } 
} 
+0

你能证明你的'ts'代码的其余部分的原因是什么? –

+0

感谢您的回复@Med_Ali_Rachid,我添加了ts代码的其余部分。 –

回答

0

发生的事情是非常正常,因为创建乌尔组元时,isClicked = false并且您的formArray已包含一个FormControl,因为此条件,开始时未显示:<span *ngIf="isClicked">

当您添加新的Cont转到FormArray,现在它包含两个FormControl s和isClicked变成true,并且显示了两个formControl

这个

的这种行为

希望它能帮助:)

+0

的确,这是问题所在。 –