'How to store and use angular pipe result to add ngClass in html file
What I am doing:
html file
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": someArray | inArray:result.id}'>
</div>
</div>
ts file:
someArray = [1, 2, 3]
results = [
{id:1, name:'abc'},
{id:2, name:'xyz'},
{id:4, name:'pqr'}]
Result: I never get assigned class.
How can I store result of pipe in html file using "as" to use it in ngClass?
inArray (pipe): Pipe returns true or false based on if value exists in array.
Referred Angular 2 add style based on pipe result:
Update 1:
inArray (pipe): Pipe returns -1 or index value based on if value exists in array.
UPDATE 2: stackblitz
Solution 1:[1]
You can try something like this - bind the class name to the property binding and use your pipe
[class.myclass]='someArray | inArray:result.id'
Your pipe will return true or false based on the condition the class will be added to the specific html
Hope this helps - happy coding :)
Solution 2:[2]
The pipes should be used to transform values.
Try using a simple function to check this:
inArray(value, theArray) {
return theArray.includes(value);
}
and the template:
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": inArray(result, results)}'>
</div>
</div>
or even without the function:
<div *ngFor='let result of results'>
<div [ngClass]='{"myclass": results.includes(result)'>
</div>
</div>
Good luck!
Solution 3:[3]
In my case I used a directive with inputs, when the directive inputs change, the required style can be calculated and applied on the directive input. Taken from answers here: Angular2 Styles in a Directive
Solution 4:[4]
You can use function for this : [ngClass]="isValueInArray()" and return value true/false in that function
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahul |
| Solution 2 | Andrew Radulescu |
| Solution 3 | Eli |
| Solution 4 | Shifali singla |
