代码之家  ›  专栏  ›  技术社区  ›  Dino

角度4子视图未更新

  •  0
  • Dino  · 技术社区  · 6 年前

    我的结构如下:

    <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数组,并希望在子组件中呈现它。我试过使用 一旦改变 在子组件上,但当我将新对象推送到数组时,并没有触发任何更改。

    我通过创建一个可观察项并将新添加的项发送到子组件,成功地完成了“变通”。我希望如何将数组作为一个整体发送给子组件,而不是逐个项发送项。

    以下是具有可观察性的解决方案:

    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();
     })
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Sachin Gupta    6 年前

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

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