0

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

2
  • try *ngIf="message.addressDescription?.indexOf('Maple') with a nullable operator Commented Nov 3, 2019 at 10:08
  • hi @terahertz hmm, that get rids of compilation error, now its rendering the html item, even if Maple does not exist, I just tried <app-address-mailing *ngIf="message.addressDescription.indexOf('randomwordrandomwordrrandomword') > -1"></app-address-mailing> , and displays without really checking if statement, strange Commented Nov 3, 2019 at 10:11

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments