问题
I am new to angular and currently using angular 5 i want to add check box and drop down list on click event() using Reactive form control. Please suggest a solution.
回答1:
Your html template should look something like below:
<div formArrayName="items" *ngFor="let item of items.controls; let i=index">
<div [formGroupName]="i" class="well">
<input type="checkbox" formControlName="isChecked" />
</div>
<div *ngIf="isChecked.invalid && (isChecked.dirty || isChecked.touched)"
class="alert alert-danger">
<div *ngIf="isChecked.errors.required">
Checkbox is required.
</div>
</div>
</div>
<button type="button" (click)="addItem()">Add Item</button>
Component file should contain a FormGroup with a FormArray called items defined in it.
this.formGroup = this.formBuilder.group({
items: this.formBuilder.array([])
})
The below code is a getter property for easy access.
get items(): FormArray {
return this.formGroup.get('items') as FormArray;
}
To add a checkbox on click.
private addItem(): void {
this.items.push(this.buildItem());
}
private buildItem(): FormGroup {
return this.formBuilder.group({
id: [''],
isChecked: [false, Validators.required],
});
}
Note: I haven't tried it so correct the syntax as necessary.
来源:https://stackoverflow.com/questions/50117678/add-checkbox-dynamically-using-angular-2