Angular bind ! of Boolean property

It seems like a trivial task. In an Angular app change a checkbox that manages the Deleted ‘soft delete’ property to invert and show as an Active property.

So the naive approach is just to try and change the two way model binding to ! the boolean value – something like:

<input name="IsDeleted" type="checkbox" [(ngModel)]="!input.IsDeleted">
<input name="IsDeleted" type="checkbox" class="form-control" [(ngModel)]="!input.IsDeleted" [disabled]="!canWrite">

Frighteningly this very nearly works! But you will find the behaviour of the model set is not correct, requiring two clicks on the check box – to be fair the docs do say to only set a data-bound property. So what do you do?

To stick with the two way data-binding syntax you could add getter/setter accessors on the component itself:

get isActive() { return !this.input.IsDeleted; } set isActive(newValue: boolean) { this.input.IsDeleted = !newValue; }

then use these as the target of the two way data-bind expression:

<input name="IsDeleted" type="checkbox" [(ngModel)]="isActive">

Personally I think a more elegant is to use the one way binding to display the inverted value and the event syntax (for the checkbox the change event) the set the inverted value:

<input name="IsDeleted" type="checkbox" class="form-control" [ngModel]="!input.IsDeleted" (change)="input.IsDeleted=!$event.target.checked" [disabled]="!canWrite">
<input name="IsDeleted" type="checkbox" [ngModel]="!input.IsDeleted" (change)="input.IsDeleted=!$event.target.checked">

Add comment

Loading