javascript - 角度:使用 ngFor 为段落设置不同的颜色
问题描述
当我点击一个按钮时,我将字符串添加到一个数组中,我需要在页面中显示这些字符串。但我只需要在第 5 个元素之后显示红色文本(前 5 个元素应该有黑色文本)。这是我尝试过的:
组件代码:
import { Component } from '@angular/core';
@Component({
selector : 'app-toggle',
templateUrl : './toggle.component.html',
styleUrls : ['./toggle.component.css']
})
export class ToggleComponent {
toggleState = false;
clickNumber = 0;
actions = [];
action = 'Display';
onClick() {
this.clickNumber++;
this.toggleState = !this.toggleState;
if (this.toggleState) {
this.action = 'Display';
} else {
this.action = 'Hide';
}
this.actions.push('click number: ' + this.clickNumber.toString() + ', changed the state to ' + this.action);
}
getColor(): string {
if (this.clickNumber > 5) {
return 'red';
} else {
return 'black';
}
}
}
和html代码:
<button (click)="onClick()" >{{action}} details</button>
<p *ngIf="toggleState">Password details: secret</p>
<p *ngFor="let act of actions" [ngStyle]="{'color' : getColor()}">{{act}}</p>
但我的问题是,在我点击超过 5 次后,所有段落元素都会改变文本颜色。那么如何实现呢?我做错了什么?我正在使用角度 6。
这是我的页面的外观:
解决方案
您可以使用 index 的属性*ngFor
,以及ngStyle
像这样:
<p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
推荐阅读
- go - 无法打开应位于基本路径中的文件
- android - 深度链接中的Android路径模式
- javascript - 未显示成功警报
- php - 根据我的代码在服务器端实现长轮询
- python - Python 请求请求导致 400 错误,而 cURL 请求正常
- html - 如何在 jekyll 中设置大小/旋转图像?
- codenameone - 代号一 存储和文件系统存储空间占用、可用空间、文件列表和清除
- java - Azure 中带有 java 示例的 Worker 角色
- android - 无法向 Github API 发出 POST 请求
- java - SQLite 似乎没有在带有 onCheckedChanged 的 Android RecyclerView 中执行