我正在尝试解决 AngularJS 中不存在的问题,因为 $digest
-循环会检查所有内容。
我正在尝试创建一个组件,它可以自行初始化(异步)并通知其周围的容器加载已完成。
我有这个伪表:
<my-table>
<ng-container *ngFor="let row in rows">
<my-table-row
[row]="row"
[isLoading]="row.isLoading"
(click)="onClickRow(row)"
></my-table-row>
<my-detail-row *ngIf="row.isExpanded">
<my-component
[data]="row"
></my-component>
></my-detail-row>
</ng-container>
</my-table>
在周围的组件(包含行
)中,我有函数onClickRow(row)
,它切换row.isExpanded
。
在 my-component
组件中,我想将 row.isLoading
设置为 true(通知“父”行它正在加载),然后将其设置为 false API 调用完成后。
@Input() data: any;
ngOnInit() {
this.task.isLoading = true; // PROBLEM
setTimeout(() => { // simulate API call
this.task.isLoading = false; // no problem
}, 2000);
}
现在我收到此错误:错误:ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。先前的值:“未定义”。当前值:'true'。
我猜这是因为变化是从 my-component
向上到 ng-container
而不是向下到 my-table-row
?
我有一个解决方法,因为我可以使用第二个 setTimeout()
,围绕 this.task.isLoading
的第一个设置,但这会导致一些 popin -effects,如果可能的话,我想找到一个更清洁的解决方案。
有没有人有建议,这是如何工作的?
最佳答案
我找到了一个我可以接受的解决方案。
您可以将“父级”注入(inject)到您的组件中(类似于 AngularJS 中的 require
)。
为此,您需要合并 my-table-row
和 my-detail-row
变成类似 my-item-row
的东西.这有额外的好处,您可以将切换逻辑放入组件中,而不必在每次使用时都重新实现它。
my-item-row.component.html
:
<div
class="item-row"
(click)="onToggleDetail()"
>
<div class="cell">...</div>
<div *ngIf="isLoading" class="loading"></div>
</div>
<div
*ngIf="isExpanded"
[hidden]="!isInitialized"
class="detail-row"
>
...
</div>
my-item-row.component.ts
:
import { Component } from '@angular/core';
import { Input, ChangeDetectorRef } from '@angular/core';
@Component({...})
export class MyItemRowComponent {
...
isInitialized: boolean = false;
isLoading: boolean = false;
isExpanded: boolean = false;
constructor(private changeDetector: ChangeDetectorRef) { }
onToggleDetail() : void {
this.isExpanded = !this.isExpanded;
}
public startLoading() : void {
this.isLoading = true;
this.isInitialized = false;
this.changeDetector.detectChanges(); // trigger re-evaluate
}
public stopLoading() : void {
this.isLoading = false;
this.isInitialized = true;
this.changeDetector.detectChanges(): // trigger re-evaluate
}
}
现在,您可以将其注入(inject) my-component
,像这样:
my-component.component.ts
:
import { Component } from '@angular/core';
import { Input, Host, Optional } from '@angular/core';
import { MyItemRowComponent } from '...';
@Component({...})
export class MyComponentComponent {
...
// Optional, because there may be a case where we want to use it outside of a row
constructor(@Optional() @Host() private parent: MyItemRowComponent) { }
ngOnInit() { // or ngAfterViewInit, doesn't matter
if (this.parent) {
this.parent.startLoading();
}
setTimeout(() => { // simulate API call
if (this.parent) {
this.parent.stopLoading();
}
}, 2000);
}
}
这是我目前的解决方案。
这会导致 my-component
出现不同的问题正在启动,即使尚未展开,请参阅此处:
关于 Angular 变化检测 ExpressionChangedAfterItHasBeenCheckedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44922384/