1

*ngIf当指令基于异步条件时,如何摆脱上述错误?

在我的主要组件 ( products.ts) 中,我订阅了一个 observable,这是用户选择的结果,他可以通过与许多组件(包括products.ts)交互来实现。在此组件的模板 ( products.html) 中,我需要检查是否选择了任何产品,如果是,则显示它们的编号。

这一切都很完美,但我想摆脱这个错误。

产品.ts

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

产品.html

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

2 回答 2

1

使用异步管道。(您甚至不需要在组件内订阅。)

产品.ts

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

在模板中使用异步管道:

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

也无需取消订阅。异步管道也处理这个问题。

于 2020-01-02T15:34:20.580 回答
0

当您在角度变化检测运行后更改数据时会发生这种情况。它通常发生在您更改 ngAfterViewInit 生命周期中的数据时。你在这个生命周期中运行一些东西吗?

于 2020-01-02T15:34:54.090 回答