Ng If with Angular for String Contains

ng if with angular for string contains

ES2015 UPDATE

ES2015 have String#includes method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true if the needle is found in haystack else returns false.

ng-if="haystack.includes(needle)"

Here, needle is the string that is to be searched in haystack.

See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.


You can use String#indexOf to get the index of the needle in haystack.

  1. If the needle is not present in the haystack -1 is returned.
  2. If needle is present at the beginning of the haystack 0 is returned.
  3. Else the index at which needle is, is returned.

The index can be compared with -1 to check whether needle is found in haystack.

ng-if="haystack.indexOf(needle) > -1" 

For Angular(2+)

*ngIf="haystack.includes(needle)"

Angular see if String is Within Another String, using Substring and ngIf

As the error suggests:

message.addressDescription is undefined.

So you can add a new condition:

*ngIf="message?.addressDescription && message.addressDescription.indexOf('Maple') > -1"

With this condition, you will be sure that it's valid.

How can I use ng-if to check if the string contains others substrings?

Per you requirement, what you need to use actually is ngClass

ng-class="{'teamA': msg.indexOf('#teamA') > -1, 'teamB': msg.indexOf('#teamB') > -1}" 

Then you only need one element

<ion-item ng-class="see above...">            
{{msg}}
</ion-item>

Angular ngIf check if variable starts with a specified character in component html

Use startsWith method like this

<div *ngIf="name.startsWith('@')">
Show something
</div>

And if you want to check if string doesn't start with '@' simply add '!' like *ngIf="!name.startsWith('@')"

Check if a string starts with certain character using ngIf and display it

You can try this.

<h3 *ngIf="article.barcode_no.indexOf('S',0) == 0 "> Kod Bar    : {{ article.barcode_no.substring(1) }} </h3>

Stackblitz demo

Angularjs: ng-if display content by comparing the string

Just remove the expression {{}},

   <img ng-if="message.messageType =='image'" ng-src="img/adam.jpg"></img>
<p ng-if="message.messageType =='text'">{{message.content}}</p>


Related Topics



Leave a reply



Submit