首页 > 解决方案 > 角度:使用 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。

这是我的页面的外观:

在此处输入图像描述

标签: javascriptangulartypescriptng-style

解决方案


您可以使用 index 的属性*ngFor,以及ngStyle像这样:

<p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>

推荐阅读