thrashead
thrashead

Reputation: 337

Cannot read property 'Description' of undefined in Angular

In my Angular 4 project, project works fine but i get some errors like "Cannot read property 'Description' of undefined" in console window 40 times.

My html codes are like below;

<div [innerHtml]="helpObject.Description"></div>

And here is my component codes;

export class FooterComponent {
   helpObject: any;

   errorMsg: string;

   constructor(private _emService: EmService) {
   }

   ngOnInit() {
      this._emService.getContent("help")
        .subscribe(resData => this.helpObject = resData,
            resError => this.errorMsg = resError);
   }
}

Upvotes: 0

Views: 156

Answers (1)

wentjun
wentjun

Reputation: 42556

You're probably making a rookie mistake here, but this could be solved by making use of the safe navigation operator on your helpObject to protect it from null or undefined values while you are waiting for the data (which is undefined at that very moment) to be rendered:

<div [innerHtml]="helpObject?.Description"></div>

Alternatively, you can use an *ngIf to solve your issue. This prevents that div from being rendered until helpObject is defined.

<div *ngIf="helpObject">
..
<div [innerHtml]="helpObject?.Description"></div>
..
</div>

Upvotes: 1

Related Questions