【问题标题】:Angular 4 ngIf not toggled after variable being updated in ngOnInit在 ngOnInit 中更新变量后,Angular 4 ngIf 未切换
【发布时间】:2018-01-11 02:19:13
【问题描述】:

我正在使用 Angular v4 并且在我的模板中有一个 *ngIf:

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

在我的组件文件中,我有:

public products = [];

....

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

但是,在设置products 之后,ngIf 将不会被切换。当我添加一个按钮并手动设置变量时,ngIf 将被切换!

我尝试将 if 语句更改为 products?.length &gt; 0,但效果不佳。

【问题讨论】:

  • 添加console.log时是否看到this.products?
  • 试试this.products = [...data]
  • @Sajeetharan 是的,我确实在 console.log 中看到了 this.products。正在设置该值,但未切换 ngIf。
  • @chrisz 不起作用... :(

标签: javascript angular angular-ng-if


【解决方案1】:

从这篇文章中找到了我的答案: Triggering change detection manually in Angular

根据Angular的文档https://angular.io/api/core/ChangeDetectorRef

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

因此,通过应用 detectChanges,Angular 将手动检查和更新节点。

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2019-04-27
    • 2019-03-25
    • 1970-01-01
    • 2018-06-22
    • 2018-05-08
    • 2018-04-29
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多