我正在使用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);
}
}
你能證明你的'ts'代碼的其餘部分的原因是什麼? –
感謝您的回覆@Med_Ali_Rachid,我添加了ts代碼的其餘部分。 –