如何存储和使用角度管道结果在html文件中添加ngClass

问题描述 投票:0回答:4

我在做什么:

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

angular angular-pipe
4个回答
1
投票

如果我没错,这就是你要找的!

对不起,我得照顾一些东西,现在才回来..

检查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示例中一起工作。


1
投票

应该使用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>

祝好运!


1
投票

您可以尝试这样的事情 - 将类名绑定到属性绑定并使用您的管道

[class.myclass]='someArray | inArray:result.id'

根据将类添加到特定html的条件,您的管道将返回true或false

希望这有帮助 - 快乐编码:)


0
投票

你可以使用函数:[ngClass] =“isValueInArray()”并在该函数中返回值true / false

© www.soinside.com 2019 - 2024. All rights reserved.