Angular 4 subview 不更新

标签 angular

我的结构如下:

parent.component.html

<listing-categories #listingCategories [categories]="listingsPaths"></listing-categories>

parent.component.ts

this.listingsPaths = [];
for (let category of listing.categories) {
    // Subscribing to a service and pushing the data to an listingPaths
    this._projectService.getCategories().subscribe((data) => {
     this.listingsPaths.push(data);
    });
}

child.component.ts

@Input() public categories;

child.component.html <强> ...

如您所见,我想发送在 promise 中填充的 listingPaths 数组,并且我想在子组件中呈现它。我已经尝试在子组件上使用 OnChanges,但是当我将新对象推送到数组时没有触发任何更改。

我设法通过创建一个 Observable 并将新添加的项目发送到一个子组件来“变通”。我怎么想将一个数组作为一个整体发送到子组件,而不是一个项目一个项目地发出。

这是 Observable 的解决方案:

parent.component.ts

_listingPaths = new Subject<any>();
_listingPathsChanges$ = this._listingPaths.asObservable();

在 for 循环中,我不是将项目推送到数组,而是将其发送到子组件:

this._listingsPaths.next(data);

child.component.ts

 this.categories.subscribe((data) => {
     this._categories.push(data); // I don't want this part, I want to receive whole array from a parent
     this.cd.markForCheck();
 })

最佳答案

您是否在您的子组件中设置了 ChangeDetectionStrategy.OnPush?如果是,那么您可能需要将其删除。数组中的任何更改都不是对象引用的更改,因此不会触发更改检测周期。

或者,您可以创建一个可观察对象并使用异步管道 (observable$ | async) 将数据发送给子对象。

关于Angular 4 subview 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486340/

相关文章:

javascript - 删除特定项目(索引)方法

angular - 从 HTTP JSON 中提取数据

css - 强制 Angular cli gz 生成

angular - @angular/cli 6.0 tslint teamcity 格式不再起作用

Angular2 http 响应正文出错

angular - Angular 项目的 bundle 大小?

在生产中部署 Angular 应用程序 - 获取不同的 cli 版本

unit-testing - Angular 2 : How to mock ChangeDetectorRef while unit testing

javascript - 突出显示已编辑的 Angular 表格单元格

angular - 如何以编程方式检查 formcontrol 在 Angular 中是否有效?