【问题标题】:ngStyle table based on arrays value基于数组值的 ngStyle 表
【发布时间】:2019-06-11 13:56:13
【问题描述】:

我想得到一个这样的表:

我有 2 个对象

  users = [
    { name: 'john', age: '22' },
    { name: 'mike', age: '20' },
    { name: 'dan', age: '12' },
    { name: 'anne', age: '16' },
    { name: 'jenny', age: '42' },
  ]

  names = [
    { name: 'john', color: 'black' },
    { name: 'mike', color: 'black' },
    { name: 'dan', color: 'red' },
    { name: 'anne', color: 'red' },
    { name: 'jenny', color: 'red' },
  ]

如果来自names 的名称在users 中,我希望它的颜色在表格内为black,如果不是,我希望它是red

这是我的html:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let user of users">
            <ng-container *ngFor="let x of names">
                <ng-container *ngIf="x.name == user.name">
                    <td [ngStyle]="{ 'color': names.color }">{{ user.name }}</td>
                    <td [ngStyle]="{ 'color': names.color }">{{ user.age }}</td>
                </ng-container>
            </ng-container>
        </tr>
    </tbody>
</table>

但它不能正常工作。 You can see a working snippet here

我怎样才能实现我想要的?感谢您的宝贵时间!

【问题讨论】:

    标签: html angular angular6


    【解决方案1】:

    您在引用 color 时有错字。 color 是对象的属性,而不是您正在循环的数组:

    <td [ngStyle]="{ 'color': names.color }">{{ user.name }}</td>
    <td [ngStyle]="{ 'color': names.color }">{{ user.age }}</td>
    

    应该是

    <td [ngStyle]="{ 'color': x.color }">{{ user.name }}</td>
    <td [ngStyle]="{ 'color': x.color }">{{ user.age }}</td>
    

    【讨论】:

      【解决方案2】:

      您可以创建一个根据名称(您放入组件中的名称)检索颜色的方法

      getColor(name) {
        return this.names.find(e => e.name === name).color;
      } 
      

      并调用

      <td [style.color]="getColor(user.name)">{{ user.name }}</td>
      <td [style.color]="getColor(user.name)">{{ user.age }}</td>
      

      当你这样使用它时,你不需要你的双循环,但它仍然需要为每次迭代做一个查找循环。

      更好的是将之前的两个数组结合起来使用

      combined = [];
      
      
      constructor() {
        this.combined = this.users.map(e => Object.assign(e, this.names.find(x => x.name === e.name)))
      }
      

      用法

          <tr *ngFor="let user of combined">        
              <td [style.color]="user.color">{{ user.name }}</td>
              <td [style.color]="user.color">{{ user.age }}</td>
          </tr>
      

      【讨论】:

      • 我选择了第一种方式。我还必须添加if (this.names.find(e =&gt; e.name === name) != undefined) { return ... },因为我在控制台中有一些错误。谢谢。
      猜你喜欢
      • 2013-04-06
      • 2013-03-26
      • 1970-01-01
      • 2012-10-23
      • 2012-05-11
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多