1

How do get rid of the mentioned error when *ngIf directive is based on an asynchronous condition?

In my main component (products.ts) I am subscribed to an observable, that is a result of a user's selection, which he can make through interacting with many components (including products.ts). In the template of this component (products.html) I need to check if any products are selected and if so, display their number.

It all works perfectly, but I'd like to get rid of the error.

Product.ts

  ngOnInit() {
    this.productService.getProducts().subscribe(data => {
      this.products = data;
      this.countProducts = this.products.length;
    });
  }

Product.html

  <span *ngIf="countProducts" [matBadge]="countProducts"></span> //if countProduct is not 0 or undefined, display the number of products
stanjaslaw
  • 81
  • 1
  • 4

2 Answers2

1

Use the async pipe. (You don't even need to subscribe within the component.)

Product.ts

public products$ = this.productService.getProducts();

use the async pipe in the template:

<span *ngIf="(products$ | async)?.length" [matBadge]="(products$ | async)?.length"></span>

There is also no need to unsubscribe. The async pipe handle this, too.

brandt.codes
  • 923
  • 2
  • 9
  • 19
  • Unfortunately, I cannot do that since I need this.products for other functions in this component as well. – stanjaslaw Jan 02 '20 at 15:50
  • This works also on other places in the component (in template). In 99% you don't need to subscribe within the component itself. Just `pipe`. Use the async-pipe in the template. AND: there is nothing wrong to combine this. Use the `subscribe`in component. And async pipe in the template. You get the same value. – brandt.codes Jan 02 '20 at 15:58
  • Thank you again, although I've tried with async pipe and the result is the same - everything still works, but the error in the console persists. – stanjaslaw Jan 02 '20 at 17:15
0

This happens when you change data after angular change detection has run. It happens usually when you change data in ngAfterViewInit lifecycle. Do you run something in this lifecycle?

Vugar Abdullayev
  • 1,852
  • 3
  • 21
  • 46