【问题标题】:*ngIf... when data is empty, set disabled=true for mat-checkbox*ngIf... 当数据为空时,为 mat-checkbox 设置 disabled=true
【发布时间】:2019-10-02 07:07:43
【问题描述】:

我有以下代码:

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

如果contactInfo.privateMobile 为空,我不希望用户能够选中复选框。

我尝试过类似&lt;mat-checkbox *ngIf={{contactInfo.privateMobile}} === null disabled=true" class="item"&gt;{{contactInfo.privateMobile}}&lt;/mat-checkbox&gt; 的方法,但这不起作用或无法编译。也许我需要在我的 TypeScript 代码中使用一个方法?不知道该怎么做。

【问题讨论】:

    标签: html angular angular-material angular-ng-if


    【解决方案1】:

    不必在*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

    【讨论】:

      【解决方案2】:

      你可以像这样绑定属性:

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

      如果这不起作用,这应该:

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

      【讨论】:

        【解决方案3】:

        ngIf 指令将从 DOM 中删除元素。在禁用属性中使用三元运算符

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

        Example

        【讨论】:

          猜你喜欢
          • 2022-01-14
          • 1970-01-01
          • 2017-06-28
          • 2013-12-03
          • 2019-11-25
          • 2023-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多