mat-checkbox does not check if condition is false (only on double click)

那年仲夏 提交于 2020-03-03 10:48:50

问题


I have an entity that has a variable that needs to be the opposite of the checkbox state.

enitity.enabled = true

The checkbox is there to "mark to delete" the item. If you mark and send the form, the item marked is soft deleted.

With this in mind, the checkbox is exactly like this:

<mat-checkbox [(ngModel)]="!entity.enabled">{{!entity.enabled}}</mat-checkbox>

For some reason, the enitity.enabled value is only changed when the second click applies.

I looked a lot for a solution or if this is a bug, nothing found I came here for your help.

Any idea how to fix this issue?

Example here


回答1:


You cannot use the negation operator with ngModel.

<mat-checkbox [(ngModel)]="entity.enabled">{{!entity.enabled}}</mat-checkbox>

Try it this way.

Another approach is to react on the click- or change-event

HTML

<mat-checkbox [checked]="entity.enabled" (change)="onChange()">{{!entity.enabled}}</mat-checkbox>

TypeScript

private onChange(): void {
   this.entity.enabled = !this.entity.enabled;
}

private onClick(): void {
  this.entity.enabled = !this.entity.enabled;
}


来源:https://stackoverflow.com/questions/50067083/mat-checkbox-does-not-check-if-condition-is-false-only-on-double-click

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