【问题标题】:Angular 4 - Add Class if ngModel is not emptyAngular 4 - 如果 ngModel 不为空,则添加类
【发布时间】:2017-08-25 20:48:24
【问题描述】:

如果我为选择元素定义的 ngModel 不为空,我如何向页面上的元素添加类。目前有这个..

<md-select placeholder="Location" name="location" [(ngModel)]="selectedLocation">
      <md-option *ngFor="let option of locationOptions" [value]="option.value">
        {{option.viewValue}}
      </md-option>
    </md-select>

如果 ngModel 不为空,想在 span 元素中添加一个类,类似这样...

<p>Location:<span ng-class="{'complete': selectedLocation.length > 0}">{{ selectedLocation }}</span></p>

【问题讨论】:

  • 改用[ngClass]。检查文档https://angular.io/api/common/NgClass

标签: javascript html angular if-statement material-design


【解决方案1】:

使用[ngClass]

作为example from docs

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

【讨论】:

    【解决方案2】:

    它需要在括号之间才能绑定到您的变量。另外你的 ng-class 属性是错误的,它需要是ngClass

    <p>Location:<span [ngClass]="{'complete': selectedLocation.length > 0}">{{ selectedLocation }}</span></p>
    

    【讨论】:

    • 当我尝试上面的方法时,我在控制台中收到此消息...'无法绑定到'ng-class',因为它不是'span'的已知属性
    【解决方案3】:

    我不知道 angular4 但在 angular 1 中它是这样的。

    <div ng-class="{'myClass':myModel}"></div>
    

    【讨论】:

    • 我错过了将我的课程放在单引号下,试试看。如果它仍然不起作用,那么只知道 angular4 的人可以帮助你
    【解决方案4】:

    这里有一个使用 [class] 的案例,因为您只有一个类可以申请:

    <p>Location:<span [class.complete]="selectedLocation.length > 0">{{ selectedLocation }}</span></p>
    

    我认为要短得多。

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2017-12-05
      • 1970-01-01
      相关资源
      最近更新 更多