Add checkbox dynamically using angular 2

心不动则不痛 提交于 2020-01-14 04:46:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!