Arun Kumar Arun Kumar - 3 months ago 182
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
in the
array and highlight it with some colors.

I wanted to add
class to the matched

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)) { = true;
} else {
this.items.push(text); = false;

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

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

<li *ngFor="let item of items">

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download