【问题标题】:Angular 6 *ngFor display different styles for first, odd, even and lastAngular 6 *ngFor 为第一个,奇数,偶数和最后一个显示不同的样式
【发布时间】:2019-04-15 19:45:34
【问题描述】:

我正在学习 Angular 6,只是想把我学到的一些东西放在一起,我目前遇到了一个我找不到答案的问题。我正在尝试使用 *ngFor 更改 LI 的样式,具体取决于索引是 First、Last、Odd 还是 Even。到目前为止一切正常,但我不知道如何为 Last 做这件事,因为我在列表中添加了一个新对象,它显然是最后一个,所以它为最后一个渲染颜色。

我知道该怎么做,但真正的问题是我正在从表单动态地将东西添加到我的列表中,我不确定如何评估 Last 以使其他内容变为正确的颜色。

请记住,我还是个新手,它可能看起来很乱,而且我也明白我正在做的一些客户端验证可能不是自 HTMl5 以来的最佳或必需的,但我学习它。

这是我的 HTML 组件代码

>

<h1>List of courses :</h1><br>
<div *ngIf="courses.length > 0; then coursesList else noCourses"></div>

<ng-template #coursesList>
  <h2>List of Courses :</h2>
  <ul *ngFor="let course of courses; index as i;">
    <li [ngStyle]="{'background-color':getColor(i)}" style="color: white;">
      <strong>Index : </strong>{{i}} <strong>ID : </strong>{{course.id}} <strong>Name</strong> : {{course.name}}
      <button (click)="onRemove(i)">Remove</button>
      <button (click)="onModify(i)">Modify</button>
    </li>
  </ul>
</ng-template>
<ng-template #noCourses>
  <h5>There are no courses in this list. Use the form bellow to add some.</h5>
</ng-template>

<div (keyup.enter)="onAdd()">
  <span>ID : <input type="number" (keypress)="checkNumber($event)" [(ngModel)]="fields.id" placeholder="Enter an ID"></span>
  <span>Name : <input type="text" [(ngModel)]="fields.name" placeholder="Enter a NAME"></span>
  <button (click)="onAdd()">Add</button>
  <button (click)="onClear()">Clear</button>
</div>
<div *ngIf="isNotNumber" style="background-color: red; color:black"><strong>ID can only be numbers !</strong></div>
<div *ngIf="noValues" style="background-color: red; color:black"><strong>Please fill all fields !</strong></div>
<div *ngIf="noModifyValues" style="background-color: red; color:black"><strong>To modify enter all informations!</strong></div>

.TS 的代码

>

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  noValues: boolean;
  noModifyValues: boolean;
  isNotNumber: boolean;
  fields: Courses = {id: null, name: null};
  courses: Array<Courses> = [];
  viewMode: string = null;

  checkNumber($event) {
    if ($event.keyCode != 13) {
      isFinite($event.key) ? this.isNotNumber = false : this.isNotNumber = true;
    }
  }

  onAdd() {

    if (!this.fields.id || !this.fields.name) {
      this.noValues = true;
    } else {
      this.courses.push({id: this.fields.id, name: this.fields.name});
      this.fields.id = null;
      this.fields.name = null;
      this.noValues = false;
    }
  }

  onRemove(i) {
    this.courses.splice(i, 1);
  }

  onClear() {
    this.courses = [];
    this.fields.id = null;
    this.fields.name = null;
    this.noValues = false;
  }

  onModify(i) {
    if (!this.fields.id || !this.fields.name) {
      this.noModifyValues = true;
    } else {
      this.courses[i].name = this.fields.name;
      this.courses[i].id = this.fields.id;
      this.noModifyValues = false;

    }
  }

  getColor(i){
    if (i % 2 === 0 && i != 0){i = 'odd';}
    switch (i) {
      case i = 0 : return 'orange';
      case i = 'odd' : return 'blue';
    }
    return 'red';
  }
}
interface Courses {
  id: number;
  name: string;
}

Image of the code in action for better understanding.

【问题讨论】:

  • 如果你只想改变背景颜色,你可以使用 [style.background-color] 并且你可以在 .html 中使用三元运算符,看我的回答

标签: arrays angular typescript angular6


【解决方案1】:

如果您只想更改背景颜色,您可以使用 [style.background-color] 并且可以在 .html 中使用三元运算符

<ul *ngFor="let course of courses; let index=i;
                                   let odd=odd;
                                   let last=last;
                                   let first=first">
    <li [style.backgound-color]="first?'orange':last?'purple':odd?'blue':'red'">
          ...
    </li>
</ul>

【讨论】:

  • 这是一种很好的方法,我想先这样做,但我不知道你可以在这样的绑定上在短 IF 中使用多个条件。顺便说一句,这两种方式的性能有区别吗?我知道这只是一种风格,但是如果我们有很多价值观呢
  • 如果你有很多值,你可以使用 [className]="first?'class1':... 其中 'class1', 'class2' 是在你的 component.css 中定义的样式。在性能方面,三元运算符总是更快。我不想调用函数,但我不确定性能
  • 感谢您的意见。我一定会查一下的。
  • 当我设置 last = last 时,人们看起来非常奇怪,并且有人质疑我是否知道自己在做什么。语法的光学告诉他们 last 已经在作用域中声明并且不需要重新分配,更不用说分配给同名的变量了。我向他们展示了如果我不将 last 分配给 last 会发生什么,但反应是 哦,你一定是在别处犯了错误,这不是t 看起来正确。我不想成为一个自大的 SOB 并创造有感染力的氛围。有一个链接解释了非角度为什么会以非角度的术语解释?
  • @KonradViltersten,当谈论结构指令angular.io/guide/structural-directives#inside-ngfor 时,最好的查看方式是查看自己的文档(它就像另一个 *ngTemplate,$implicits 是我们在 *ngFor="let数组的变量,以及奇数、偶数、最后一个、其他变量。是的,您将“模板”中的变量分配给 *ngFor 中定义的函数-确实是 getters 函数-您可以查看源代码在 github github.com/angular/angular/blob/master/packages/common/src/….
【解决方案2】:

试试这样的

getColor(i){
    if (i % 2 === 0 && i != 0){i = 'odd';}
    if (this.courses && (this.courses.length - 1 === i)) {i = 'last'}
    switch (i) {
      case i = 0 : return 'orange';
      case i = 'odd' : return 'blue';
    }
    return 'red';
  }

希望它有效 - 编码快乐!!

【讨论】:

  • 您可以将其用作else if,以防万一:)
【解决方案3】:

谢谢拉胡尔。我缺少的部分是评估课程中是否有内容。但是,我不得不多写几行到 Odd 和 Last 如下:

getColor(i){
    if (this.courses && i != 0 && (this.courses.length - 1 === i)) {i = 'last'}
    if (i % 2 === 0 && i != 0 && i != 'last'){i = 'odd';}
    switch (i) {
      case i = 0 : return 'orange';
      case i = 'odd' : return 'blue';
      case i = 'last' : return 'purple';
    }
    return 'red';
  }

快速提问。似乎有很多 IF 和 && 以及检查特定的东西。这是正确的做法吗?

【讨论】:

    【解决方案4】:

    您可以使用 if else 阶梯,而不是像下面给出的那样混合 if else 和 switch 和 assignment

    getColor(i)
    {
      if(this.courses)
      {
      if(i==0)
          return "orange";
      else if(i==this.courses.length-1)
          return "purple";
      else if (i%2==0)
          return "red";
      else
          return "blue";
      }
    }
    

    【讨论】:

    • def 会使代码更简洁、更易于理解。感谢您的意见。
    • 当你有更简单的选择时,不要混淆,总是欢迎:)
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 2019-09-19
    • 2019-01-30
    • 2020-01-18
    • 2015-08-31
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多