Duc Duc - 5 months ago 17
TypeScript Question

How to make Angular 2 render HTML template after a promise in the component is resolved?

For my app, the

is where info of an item will be displayed. I have a service that retrieves all items using promise. I use
to retrieve the item ID from the url path, then run the service, get all items, then find the item with the ID retrieved above, and assign it to

Here is

export class ItemDetailComponent implements OnInit {
private title = 'Item Details'
private selectedItem: object

private route: ActivatedRoute,
private itemService: ItemService
) {}

ngOnInit() {
const selectedItemId = this.route.snapshot.params.itemId

return this.itemService.getAllItems()
.then((items) => {
return _.find(items, item => item.itemId === selectedItemId)
.then((selectedItem) => {
this.selectedItem = selectedItem
console.log('Inside promise', this.selectedItem)
console.log('Outside promise', this.selectedItem)

And here is
template so I could display my item, just an example:


<div *ngIf="selectedItem">
<div><label>Item ID: </label>{{selectedItem.itemId}}</div>

The app returns nothing but the title unfortunately. I then added the two
commands and found out that the one outside of the promise as well as the html template are rendered before the promise is fulfilled, and no
is available at that time. How could I force the app to execute them only after the promise is resolved in order to have the
in place for displayed?

EDIT: I added a new line in the html template to examine further:

<div><label>Item ID 1: </label>{{selectedItem.itemId}}</div>
<div *ngIf="selectedItem">
<div><label>Item ID 2: </label>{{selectedItem.itemId}}</div>

The app displays "Item ID 1:" label but with no actual id there. The console shows me an error saying that "Cannot read property 'itemId' of undefined", again confirming that the whole template is rendered before promise resolved and is not re-rendered after data is loaded. So weird.

Answer Source