Sumit Joshi
Sumit Joshi

Reputation: 25

Bind array value in HTML

The output of my data in console.log:

{TotalPendingResponseCount: 0, TotalRequestSendCount: 1, TotalRequestReceivedCount: 1, TotalRequestRejectCount: 3}

To capture these information I am holding it in array:

userData : arrayResponseCount[];
To get the result:
this.dataservice.getData(Url).
    subscribe((res: any) => 
    { this.userData = res });
  }

And my arrayResponseCount class is:

class arrayResponseCount {
  constructor(public TotalRequestSendCount: string, public TotalPendingResponseCount: string,
              public TotalRequestRejectCount: string, public TotalRequestReceivedCount: string
  ){}
}

Now I need to bind the value in HTML. For this I am using the syntex is

{{userData.TotalRequestSendCount}}

But it thrown the exception i.e. ERROR TypeError: Cannot read property 'TotalRequestSendCount' of undefined.

Do you have any idea for this?

Upvotes: 2

Views: 790

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657008

When Angular first evaluates your binding {{userData.TotalRequestSendCount}}, userData doesn't have a value yet.

Use instead

{{userData?.TotalRequestSendCount}}

to tell Angular it shouldn't try accessing TotalRequestSendCount while userData is null (it's called safe-navigation operator)

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222522

Since you are getting data from an async request, there could be a delay, you can handle with the safe navigation operator ?,

{{userData?.TotalRequestSendCount}}

Upvotes: 2

Related Questions