我在做什么:
html文件
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": someArray | inArray:result.id}'>
</div>
</div>
ts文件:
someArray = [1, 2, 3]
results = [
{id:1, name:'abc'},
{id:2, name:'xyz'},
{id:4, name:'pqr'}]
结果:我从未上过课。
如何使用“as”将管道结果存储在html文件中以在ngClass中使用?
inArray(pipe):管道根据数组中是否存在值返回true或false。
提到Angular 2 add style based on pipe result:
更新1:
inArray(pipe):管道根据数组中是否存在值返回-1或索引值。
更新2:stackblitz
如果我没错,这就是你要找的!
对不起,我得照顾一些东西,现在才回来..
仅在值存在时才应用该类。
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'inArray' })
export class inArrayPipe implements PipeTransform {
transform(value: any, exponent: any): boolean {
let result = value.indexOf(exponent);
return result > -1;
}
}
剩下的就是你的代码..但是它们都在上面的Stackblitz示例中一起工作。
应该使用pipes
来改变价值观。
尝试使用一个简单的函数来检查:
inArray(value, theArray) {
return theArray.includes(value);
}
和模板:
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": inArray(result, results)}'>
</div>
</div>
甚至没有这个功能:
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": results.includes(result)'>
</div>
</div>
祝好运!
您可以尝试这样的事情 - 将类名绑定到属性绑定并使用您的管道
[class.myclass]='someArray | inArray:result.id'
根据将类添加到特定html的条件,您的管道将返回true或false
希望这有帮助 - 快乐编码:)
你可以使用函数:[ngClass] =“isValueInArray()”并在该函数中返回值true / false