In Angular2 you should consider using a (pure) pipe for this
You could consider adding your own custom "includes" pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'includes',
})
export class Includes implements PipeTransform {
public transform(haystack: string, needle: string): boolean;
public transform<T>(array: T[], item: T): boolean;
public transform(haystack: any[]|string, needle: any|string): boolean {
return haystack.includes(needle);
}
}
This pipe would work both for finding items in an array or string in string searches.
You can use this pipe in the template as follows:
<div *ngIf="haystack | includes : needle">
//...
<div>
Note: This seems like a lot of overhead since you could just do like suggested in the other answers:
<div *ngIf="haystack.includes(needle)">
//...
</div>
But when using such a solution the includes
mehtod will be called on each change detection, even in cases where the value of haystack
didn't change. By using a pipe you will make sure it will only be executed when haystack
has changed.
See for more information on this topic the official Angular documentation on pure pipes.