Add checkbox dynamically using angular 2

2019-06-08 06:22发布

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条回答
做自己的国王
2楼-- · 2019-06-08 06:51

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.

查看更多
登录 后发表回答