user12250118
user12250118

Reputation:

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

I am doing the following, trying to check if addressDescription contains the word Maple street. Receiving the following error, how would this be fixed?

<app-address-mailing *ngIf="message.addressDescription.indexOf('Maple') > -1"></app-address-mailing>

AddressMailingComponent.html:21 ERROR TypeError: Cannot read property 'indexOf' of undefined

Resource below was not working, plus its older, new syntax is ngIf not ng-if

ng if with angular for string contains

Upvotes: 0

Views: 1210

Answers (2)

Wandrille
Wandrille

Reputation: 6821

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.

Upvotes: 1

Abolfazl Roshanzamir
Abolfazl Roshanzamir

Reputation: 14852

message is not defined, first check then use includes

if addressDescription is a sentence, try the following

<app-address-mailing *ngIf="message?.addressDescription.split(' ').includes('Maple')"></app-address-mailing>

otherwise, try the following

<app-address-mailing *ngIf="message?.addressDescription.includes('Maple')"></app-address-mailing>

Needless to say : you can apply toLowerCase method.

Upvotes: 0

Related Questions