thesystem
thesystem

Reputation: 604

*ngIf... when data is empty, set disabled=true for mat-checkbox

I have the following code:

<div class="item-container">
  <mat-checkbox class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>

If contactInfo.privateMobile is empty, I don't want the user to be able to check the checkbox.

I have tried something along the lines of: <mat-checkbox *ngIf={{contactInfo.privateMobile}} === null disabled=true" class="item">{{contactInfo.privateMobile}}</mat-checkbox>, but that doesn't work or compile. Maybe I need a method in my TypeScript code instead? Not sure how to go about it.

Upvotes: 2

Views: 2056

Answers (3)

acdcjunior
acdcjunior

Reputation: 135752

Don't have to use {{}} in the *ngIf:

<div class="item-container">
  <mat-checkbox *ngIf="contactInfo.privateMobile" class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>

If you wish to just disable it, you could do something like:

<div class="item-container">
  <mat-checkbox [disabled]="!contactInfo.privateMobile" class="item">{{contactInfo.privateMobile || '(private mobile unavailable)'}}</mat-checkbox>
</div>

Demo: https://stackblitz.com/edit/angular-h1sfoy?file=app%2Fcheckbox-overview-example.html

Upvotes: 5

Chellappan வ
Chellappan வ

Reputation: 27303

ngIf directive will remove the element from DOM. Use ternary operator in disabled property

<mat-checkbox [disabled]=" contactInfo?.privateMobile === null ? true : false">Check me!</mat-checkbox>

Example

Upvotes: 1

mbojko
mbojko

Reputation: 14679

You can bind attribute like this:

[disabled]="contactInfo.privateMobile === null"

if that doesn't work, this should:

[attr.disabled]="contactInfo.privateMobile === null ? 'disabled' : null"

Upvotes: 1

Related Questions