简体   繁体   English

Mat-Checkbox 绑定 model 可以是可选的还是 null?

[英]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.大家好,我是 angular 的新手,我在其中创建了一个动态复选框列表。 Because there are times which I will get the selected value from API which I need to bind to the checkboxes.因为有时我会从 API 中获取选定的值,我需要将其绑定到复选框。 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.我现在的主要问题是 ngModel 绑定不能是可选的,但我需要它是可选的,因为有时 API 会给我 null 列表项。 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.我还遇到了另一种跟踪 onChange 事件的方法,但它只包含被 onChanged 的复选框,不包括那些被选中的复选框。

So, I'm thinking maybe you could create another variable to bind with ngModel.所以,我想也许你可以创建另一个变量来绑定 ngModel。 In the function onChangeCheckbox you created, you could update the value of b.RefAccess.selected if it's different from null.在您创建的 function onChangeCheckbox 中,如果 b.RefAccess.selected 与 null 不同,您可以更新它的值。

The elvis operator can't be used for assignment. elvis 运算符不能用于赋值。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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