Arun Kumar Arun Kumar - 17 days ago 79
TypeScript Question

Add styles to matched items in for loop angular 2

I've a list of array items

['Mark', 'John']
.

I want to find
Mark
in the
items
array and highlight it with some colors.

I wanted to add
highlighted
class to the matched
li
tag

How can i do it angular 2? Please help



export class AppComponent {
title = 'app';
public items = ['Mark', 'John'];
show: boolean;
onSubmit(text: string) {
if (this.items.includes(text)) {
this.show = true;
} else {
this.items.push(text);
this.show = false;
}
}
}

<div class="container">
<input type="text" #text/>
<button (click)="onSubmit(text.value)">Add</button>

<div *ngIf="show">
Item Already Exits
</div>

<div>
<ul>
<li *ngFor="let item of items">
{{item}}
</li>
</ul>
</div>
</div>




Answer Source

You can conditionally set a class in angular that checks for a property.

<li *ngFor="let item of items" [class.highlighted]="item==='Mark'">{{item}}</li>

The item from the *ngFor is already accessible in the tag you are using it on. The [class.highlighted] is followed by the condition, in this case by simply checking if the current item equals Mark. So highlighted is only applied as a class if the condition is true.

Hope this helps.