I have an object of a class. This object is getting data from an API. While accessing this object in the HTML, I'm getting the error TS2532. Here's the code--
export interface TgtInfo{
Month: string;
SerTarget?: number;
IFCTarget?: number;
EmailTarget?: number;
PSFTarget?: number;
SMRTarget?: number;
SerAch?: number;
IFCAch?: number;
EmailAch?: number;
PSFAch?: number;
SMRAch?: number;
}
COMPONENT TS FILE
TGTData?: TgtInfo;
this.apiService.getTargetAchivement(this.searchObj).subscribe((data: any) => {
if(data){
this.TGTData = data ;
}
}, err => {
console.log(err);
});
COMPONENT HTML FILE
<h2>{{TGTData?.SMRTarget | number }}%</h2>
CodePudding user response:
you can add question mark like this:
<h2>{{TGTData?.SMRTarget | number }}%</h2>
and if you want to give it default value you can do it like this:
<h2>{{TGTData?.SMRTarget | number || 0}}%</h2>
CodePudding user response:
Error Code TS2532 just means that your object TGTDatais possibly undefined - obviously this makes sense when you consume api-data. It is thrown because angular trys to render the view but there is no value assigned to TGTData
The most elegant solutions is to use the ?operator from angular template syntax. The ?stops evaluating if the TGTData is null or undefined
You can also wrap your code block with an *ngIf what i would not recommend:
<h2 *ngIf="TGTData">{{TGTData.SMRTarget | number }}%</h2>
Just a side question, why do you use a class and not an interface?
Regards
Jan
