【问题标题】:Add class with [ngClass] depending on local html condition根据本地 html 条件使用 [ngClass] 添加类
【发布时间】:2019-05-07 04:32:41
【问题描述】:

我过去使用过 [ngClass],根据之前保存在 javascript/typescript 中的变量的布尔值应用类。但是我想知道是否可以根据本地 HTML 布尔值应用它?

即。

<div class="card" *ngFor="let item of data" #panel ngClass="{expanded: isExpanded}">
  <div class="header">
    <div class="itemName">Text</div>
    <div class="itemDir">Some more text</div>
    <mat-icon *ngIf="!panel.isExpanded" (click)="panel.isExpanded=true">edit</mat-icon>
    <mat-icon *ngIf="panel.isExpanded" (click)="panel.isExpanded=false">cancel</mat-icon>
  </div>
</div>

在这里,我显示的是两个图标之一,这取决于 HTML 中定义的本地 isExpanded 变量,而不是后端。

我想根据这个值应用一个类...可以吗?

Here is what I am working on

【问题讨论】:

  • backend 是什么意思?你的.ts?你的.ts 中没有isExpanded
  • &lt;div class="card" *ngFor="let item of data" #panel [ngClass]="{'expanded': isExpanded === true }"&gt;
  • @xyz - 这是正确的。 isExpanded 在 HTML 中定义
  • @Florian - 似乎对我不起作用:-(
  • 我知道你需要什么,我正在修改你的闪电战

标签: html css angular animation


【解决方案1】:

使用[class.expanded]="isExpanded"。绑定到class.expanded 胜过类属性

<div class="card" *ngFor="let item of data" #panel [class.expanded]="panel.isExpanded" [class.notExpanded]="!panel.isExpanded"> 

【讨论】:

  • 这似乎不适合我...如果它适合你,你能分叉我的闪电战并发布吗?
  • 嗯...我看到它可以改变颜色,但由于某种原因不能改变 div 的高度?我也输入了硬编码的起始尺寸,但仍然没有变化:-(
  • 您错过了高度末尾的pxheight: 300px ;
  • 我的天啊,真是个菜鸟!在 XD 向所有试图帮助我的人道歉之后,它实际上工作正常:-)
【解决方案2】:

你可以使用*ngIf="true as isExpanded"在模板上做变量

<div class="card" *ngFor="let item of [1,2,3,4];"  >
  <div class="header" *ngIf="true as isExpanded" ngClass="{expanded: !isExpanded}">
    <div class="itemName">Text</div>
    <div class="itemDir">Some more text</div>
    <div *ngIf="isExpanded" (click)="isExpanded=!isExpanded">edit</div>
    <div *ngIf="!isExpanded" (click)="isExpanded=!isExpanded">cancel</div>
  </div>
</div>

stackblitz demo??

【讨论】:

  • 从我在你的闪电战中看到的,似乎没有做任何事情:-/
【解决方案3】:
<div class="card" *ngFor="let item of data" #panel ngClass="{expanded: isExpanded}">
<div class="header">
    <div class="itemName">{{item.name}}</div>
    <div class="itemDir">{{item.directory}}</div>
    <mat-icon *ngIf="!isExpanded;else other_content" (click)="isExpanded=true">edit</mat-icon>
    <ng-template #other_content>Other Icon goes here</ng-template>
</div>

您可以通过模板引用变量来引用上面使用 If 和 else 的代码,该变量可以在图标和非图标之间正确切换

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 2021-05-31
    • 2017-05-23
    • 2023-01-04
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多