简体   繁体   中英

Mat-Checkbox binding model can it be optional or null?

Hi all I am new to angular, which I created a dynamic list of checkboxes. Because there are times which I will get the selected value from API which I need to bind to the checkboxes. Thus I will have the code like below

<div *ngFor="let b of result?.category">
                        <mat-checkbox (change)="onChangeCheckbox($event)" [value]="b.RefAccess?.accessId"
                            [checked]="b.RefAccess?.selected" [(ngModel)]="b.BoRefAccess?.selected"
                            [ngModelOptions]="{standalone: true}">
                            {{b.BoRefAccess?.accessDesc}}
                        </mat-checkbox>
                    </div>

Error "Empty expressions are not allowed ng , Parser Error: The '?.' operator cannot be used in the assignment at column 25 in [b.BoRefAccess?.selected=$event] in..."

My main problem now is the ngModel binding can not be optional but I need it to be optional because there are times API will give me null list item. So I not sure how to handle it.

I also came across another method which keep track on the onChange event but it will only consist checkboxes that being onChanged, those are selected is not included.

So, I'm thinking maybe you could create another variable to bind with ngModel. In the function onChangeCheckbox you created, you could update the value of b.RefAccess.selected if it's different from null.

The elvis operator can't be used for assignment. You should declare it in a more explicit way.

Instead of

[(ngModel)]="b.BoRefAccess?.selected"

Use

[ngModel]="b.BoRefAccess?.selected" (ngModelChange)="b.BoRefAccess.selected=$event"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM