2017-10-18 3 views
0

나는 각도 반응성 폼 작업을하고 있습니다. 폼에 동적으로 컨트롤을 추가하고 싶습니다. 하지만 컨트롤을 추가 할 때 번 두 번 처음에는 왜 그런지 잘 모릅니다. 나중에 제대로 작동합니다.각도로 반응성 폼에 컨트롤을 동적으로 추가 할 때의 문제

<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

매우 정상, UR componenet가 생성되기 때문에, isClicked = false 여기에 코드입니다 formArray에 이미 FormControl 중 하나가 포함되어 있는데이 상태로 인해 처음에는 표시되지 않습니다. <span *ngIf="isClicked">

새 Cont rol는 FormArray으로, 이제는 두 개의 FormControl을 포함하고 isClickedtrue이되고 두 개의 formControl이 표시됩니다.

이이 문제

그것을 :) 도움이

+0

정확히, 이것이 문제였습니다. –