display checkbox based on object response Angular

白昼怎懂夜的黑 提交于 2019-12-02 03:13:27

First of all when using FormBuilder try not to instantiate FormControl or FormArray directly. Instead use FormBuilder to do so.

this.form = this.formBuilder.group({
    receivedSummons: this.formBuilder.array([])
});

As your response is an array you can get multiple receivedSummons which can contain multiple data.items. You need a different form structure to solve your issue.

Your addCheckboxes function might look like this.

addCheckboxes() {
    this.formReceivedSummons.setValue([]);
    this.receivedSummons.map(x => {
        const group = this.formBuilder.group({
            header: [x.header.transactionId],
            items: this.formBuilder.array([], [minSelectedCheckboxes(1)])
        });
        x.data.items.map(y => {
            (group.get('items') as FormArray).push(this.formBuilder.group({
                name: [y.itemNo],
                isChecked: ['']
            }));
        });
        this.formReceivedSummons.push(group);
    });
}

Also change the html file accordingly.

<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
    <ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
        <ng-container [formGroup]="summon">
            <p>{{summon.value.header}}</p>
            <ng-container formArrayName="items" *ngFor="let item of formReceivedSummonsItems(i).controls; let j = index">
                <ng-container [formGroup]="item">
                    <input type="checkbox" formControlName="isChecked"> {{item.value.name}}
                </ng-container>
            </ng-container>
        </ng-container>
        <div *ngIf="!summon.valid">At least one order must be selected</div>
    </ng-container>
    <br>
    <button [disabled]="!form.valid">submit</button>
</form>

Here 2 getters were used to get the receivedSummons and items FormArray

get formReceivedSummons() {
    return this.form.get('receivedSummons') as FormArray;
}

formReceivedSummonsItems(i: number) {
    return (this.formReceivedSummons.controls[i].get('items')) as FormArray;
}

Here you can find the full demo.

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