I inherited some code in an Angular2 project which follows this pattern:
<input type="text [(ngModel)]="selectedResource.url">
The component constructor is as follows, where loadResources() is an async method that will initialize selectedResource:
constructor() {
this.loadResources();
}
The problem I run into is that since selectedResource is null until the async method completes, the page loads and angular starts throwing a bunch of errors complaining that selectedResource is null, until the async method completes, and then everything works great.
To avoid the exceptions I see two solutions - first, change the html to the following which will tell angular to check for null.
<input type="text [ngModel]="selectedResource?.url" (ngModelChange)="selectedResource.url = $event">
Alternatively I could initialized selectedResource in the page constructor. Url would initially load on the page as an empty string, but that's okay since the async method runs almost instantaneously and the user wouldn't notice.
constructor() {
this.selectedResource = new Resource();
this.loadResources();
}
Is there an established best practice for initializing data bound variables? What would be the advantages or disadvantages of each approach?