wesley.ireland wesley.ireland - 1 year ago 72
TypeScript Question

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>

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download