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
我怎样才能达到我想要的?谢谢你抽出时间!
最佳答案
您可以创建一个基于名称检索颜色的方法(放在组件中)
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>