0

I am using Angular v4 and have a *ngIf in my template:

<div class="product-list row" *ngIf="products.length > 0">
  <div *ngFor="let product of products" class="product-container">
    ...
  </div>
</div>

and in my component file I have:

public products = [];

....

public ngOnInit(): void {
  this.productsService.all().toPromise().then( (data: Product[]) => {
    this.products = data;
  });
}

However the ngIf will not be toggled after products is set. When I add a button and set the variables manually the ngIf will be toggled!

I tried changing the if statement to products?.length > 0 but it doesn't work as well.

CocoHot
  • 1,211
  • 2
  • 11
  • 18

1 Answers1

1

Found my answer from this post: Triggering change detection manually in Angular

According to Angular's documents https://angular.io/api/core/ChangeDetectorRef

detectChanges(): Checks the change detector and its children.

So by applying detectChanges Angular will manually check and update the node.

CocoHot
  • 1,211
  • 2
  • 11
  • 18