*ngIf...当数据为空时,为mat-checkbox设置disabled=true
*ngIf... when data is empty, set disabled=true for mat-checkbox
我有以下代码:
<div class="item-container">
<mat-checkbox class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>
如果 contactInfo.privateMobile
为空,我不希望用户能够选中该复选框。
我已经尝试了类似以下内容的方法:<mat-checkbox *ngIf={{contactInfo.privateMobile}} === null disabled=true" class="item">{{contactInfo.privateMobile}}</mat-checkbox>
,但它不起作用或无法编译。也许我需要在我的 TypeScript 代码中使用一个方法?不知道该怎么做。
不必在 *ngIf
中使用 {{}}
:
<div class="item-container">
<mat-checkbox *ngIf="contactInfo.privateMobile" class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>
如果你只想禁用它,你可以这样做:
<div class="item-container">
<mat-checkbox [disabled]="!contactInfo.privateMobile" class="item">{{contactInfo.privateMobile || '(private mobile unavailable)'}}</mat-checkbox>
</div>
演示:https://stackblitz.com/edit/angular-h1sfoy?file=app%2Fcheckbox-overview-example.html
您可以像这样绑定属性:
[disabled]="contactInfo.privateMobile === null"
如果这不起作用,这应该:
[attr.disabled]="contactInfo.privateMobile === null ? 'disabled' : null"
ngIf 指令将从 DOM 中删除元素。在禁用 属性
中使用三元运算符
<mat-checkbox [disabled]=" contactInfo?.privateMobile === null ? true : false">Check me!</mat-checkbox>
我有以下代码:
<div class="item-container">
<mat-checkbox class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>
如果 contactInfo.privateMobile
为空,我不希望用户能够选中该复选框。
我已经尝试了类似以下内容的方法:<mat-checkbox *ngIf={{contactInfo.privateMobile}} === null disabled=true" class="item">{{contactInfo.privateMobile}}</mat-checkbox>
,但它不起作用或无法编译。也许我需要在我的 TypeScript 代码中使用一个方法?不知道该怎么做。
不必在 *ngIf
中使用 {{}}
:
<div class="item-container">
<mat-checkbox *ngIf="contactInfo.privateMobile" class="item">{{contactInfo.privateMobile}}</mat-checkbox>
</div>
如果你只想禁用它,你可以这样做:
<div class="item-container">
<mat-checkbox [disabled]="!contactInfo.privateMobile" class="item">{{contactInfo.privateMobile || '(private mobile unavailable)'}}</mat-checkbox>
</div>
演示:https://stackblitz.com/edit/angular-h1sfoy?file=app%2Fcheckbox-overview-example.html
您可以像这样绑定属性:
[disabled]="contactInfo.privateMobile === null"
如果这不起作用,这应该:
[attr.disabled]="contactInfo.privateMobile === null ? 'disabled' : null"
ngIf 指令将从 DOM 中删除元素。在禁用 属性
中使用三元运算符<mat-checkbox [disabled]=" contactInfo?.privateMobile === null ? true : false">Check me!</mat-checkbox>