私はAngular Reactiveフォームで作業しています。私はフォームに動的にコントロールを追加したい。しかし、コントロールを追加すると、が2回追加されました。初めて、なぜそれがうまく動作するのかわかりません。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);
}
}
あなたは 'ts'コードの残りの部分を表示することができますか? –
あなたのお返事ありがとうございます@Med_Ali_Rachid、私はTSコードの残りの部分を追加しました。 –