Angular 4 ngIf 在 ngOnInit 中更新变量后未切换
Angular 4 ngIf not toggled after variable being updated in ngOnInit
我正在使用 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 > 0
,但效果不佳。
从这个 post 中找到我的答案:
根据Angular的文档https://angular.io/api/core/ChangeDetectorRef
detectChanges(): Checks the change detector and its children.
因此通过应用 detectChanges Angular 将手动检查和更新节点。
我正在使用 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 > 0
,但效果不佳。
从这个 post 中找到我的答案:
根据Angular的文档https://angular.io/api/core/ChangeDetectorRef
detectChanges(): Checks the change detector and its children.
因此通过应用 detectChanges Angular 将手动检查和更新节点。