代码之家  ›  专栏  ›  技术社区  ›  Buda Gavril

角度:使用ngfor为段落设置不同颜色

  •  2
  • Buda Gavril  · 技术社区  · 6 年前

    当我单击一个按钮时,我正在向数组中添加字符串,我需要在页面中显示这些字符串。但是我只需要在第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。

    以下是我的页面的外观:

    enter image description here

    4 回复  |  直到 6 年前
        1
  •  2
  •   user184994    6 年前

    可以使用的索引属性 *ngFor ,以及 ngStyle 就像这样:

    <p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
    
        2
  •  1
  •   Sajeetharan    6 年前

    将ngstyle与条件一起使用>5

    <p *ngFor="let act of actions; let i = index" [ngStyle]="{'color' : i > 5 ? 'red' : 'black'}">{{act}}</p>
    
        3
  •  1
  •   baao    6 年前

    如果我可以建议一个更简单的css解决方案,使用 nth-child

    p:nth-child(n+6) {
      color: red;
    }
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
    <p>
    Foo
    </p>
        4
  •  0
  •   Debojyoti    6 年前

    修正案-1: 修改 getcolor()函数

    传递当前索引值,否则 点击号码 当它是6时,所有元素都是一样的

     getColor(current): string {
        if (current > 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;let i = index" [ngStyle]="{'color' : getColor(i)}">{{act}}</p>
    

    工作示例: stackblitz