【问题标题】:Angular 4 Child View not updatingAngular 4子视图未更新
【发布时间】:2018-11-26 17:38:01
【问题描述】:

我的结构如下:

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 并使用异步管道 (observable$ | async) 将数据发送给孩子。
  • 是的,我做到了。这将是解决方案有点奇怪。如果你需要监听对象和数组的变化,那么这个人将如何处理呢?我明天试试,谢谢!
  • 阅读我的第二条评论。使用可观察的。如果您手动更新对象,请使用obj = Object.assign({},obj) 创建对象的新实例并触发更改检测。
  • 删除 ChangeDetectionStrategy.OnPush 有效。我真的很好奇为什么是这个原因,打算研究一下。谢谢!

标签: angular


【解决方案1】:

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

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

【讨论】:

  • 这个解决方案在尝试了onChanges*ngIf 之后就像魔法一样奏效。非常感谢@Sachin
猜你喜欢
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
相关资源
最近更新 更多