在渲染期间定义变量时,离子ngClass不起作用

时间:2017-12-21 11:06:00

标签: angular typescript ionic3

在渲染模板期间,我有一个奇怪的问题,即Angular in ionic:

<div class="subHeader" *ngIf="calendarid === undefined">
    <div *ngFor="let calendar of calendars; let isFirst = first" class="user"
             [ngClass]="{'active': (isFirst) }"
             (tap)="showTheCalendar(calendar.id)">
        <img src="assets/imgs/person.svg" alt="Image">
        <p>{{ calendar.name }}</p>
        <div class="selectMark"></div>
    </div>
</div>
<div class="subHeader" *ngIf="calendarid !== undefined">
    <div *ngFor="let calendar of calendars; let isFirst = first" class="user"
              [ngClass]="{'active': calendar.id===calendarid }"
              (tap)="showTheCalendar(calendar.id)">
         <img src="assets/imgs/person.svg" alt="Image">
         <p>{{ calendar.name }}</p>
         <div class="selectMark"></div>
    </div>
</div>

calendarid未定义时,该类已正确应用,但在定义时,该条件会在*ngIf中重新评估,但不会在[ngClass]="{'active': calendar.id===calendarid }"中重新评估

我开始使用Angular和Ionic,所以我可能没有反应来避免这个问题。

我也考虑过这种语法:

<div class="subHeader" *ngIf="">
    <div *ngFor="let calendar of calendars; let isFirst = first" class="user"
             [ngClass]="{'active': (isFirst && calendarid === undefined) || (calendarid === calendar.id}"
             (tap)="showTheCalendar(calendar.id)">
        <img src="assets/imgs/person.svg" alt="Image">
        <p>{{ calendar.name }}</p>
        <div class="selectMark"></div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

如果你不确定变量的类型,

使用==(关系运算符)

使用

[ngClass]="{ 'active': calendar.id == calendarid }"

而不是

[ngClass]="{ 'active': calendar.id===calendarid }"