ErickXavier
ErickXavier

Reputation: 978

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

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

Upvotes: 1

Views: 4119

Answers (1)

user6749601
user6749601

Reputation:

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;
}

Upvotes: 4

Related Questions