wesley.ireland
wesley.ireland

Reputation: 643

How do you bind the return value of an Object method to the DOM in Angular 2?

Let me make the problem a bit more specific - I can bind the return value when in an ngFor:

<select id="addTimeslotSelect" style="height:24px; background-color:rgb(235, 235, 228);"  disabled>
  <option *ngFor="let day of days" data-value="{{day}}" data-label="{{day.toDateString()}}"></option>
</select>

day.toDateString() works fine. However when I want to access a particular index outside of an ngFor I cannot seem to get it to work.

<input id="addTimeslotTextbox" data-value="{{days[days.length-1].toLocaleDateString()}}" type="text" disabled/>

days[days.length-1].toLocaleDateString() does not work here. I get the following error: "Cannot read property 'toLocaleDateString' of undefined"

Curious if anyone has insight as to why it works in the former case and not the latter.

Upvotes: 1

Views: 123

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Since on initial Change detection days array have not intialize. So you should use Navigation operator(Elvis operator) here.

data-value="{{days[days.length-1]?.toLocaleDateString()}}"

Upvotes: 4

Related Questions