【发布时间】:2017-10-18 19:18:03
【问题描述】:
我正在研究 Angular Reactive 表单。我想动态地将控件添加到表单中。但是当我添加一个控件时,它第一次添加了 两次 我不知道为什么,后来它工作正常。这是代码:
<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 代码的其余部分。
标签: angular angular-reactive-forms