Angular 为什么组件不呈现服务模型?

Angular 为什么组件不呈现服务模型?,angular,Angular,我有一个父组件,可以从服务设置获取过滤器: export class OrdersExecutionSidebarComponent { public get filters(): _Filter[] { return this.settings.filtersRepository.filters; } } 模板为: <app-filter [filter]="flt" *ngFor="let flt of filter

我有一个父组件,可以从服务
设置
获取过滤器:

export class OrdersExecutionSidebarComponent {
       public get filters(): _Filter[] {
        return this.settings.filtersRepository.filters;
    }
}
模板为:

<app-filter [filter]="flt" *ngFor="let flt of filters"></app-filter>
<span *ngFor="let f of filter.collection">{{f}}</span>
模板为:

<app-filter [filter]="flt" *ngFor="let flt of filters"></app-filter>
<span *ngFor="let f of filter.collection">{{f}}</span>

但是子组件的
@Input
没有变化

问题是过滤器是一个嵌套对象。例如,当您为Angular向
filter.collection
添加一个元素时,它仍然是同一个对象,因为它的对象引用没有改变

要解决此问题,您需要做什么:

1)不传递过滤器,只传递集合到子组件

export class FilterComponent implements OnChanges {
  @Input() collections: Collection[];
}
2)重新创建集合数组,而不是添加到集合数组中

export class FilterComponent implements OnChanges {
  @Input() collections: Collection[];
}
例如,如果您这样做,将不会触发角度变化检测:

// Still the same array!
filter.collection.push(myCollection);
虽然这将起作用:

// New array, therefore Angular will know it has to re-render!
filter.collection = [...filter.collection, myCollection];
如果必须将完整的筛选器对象传递给您的孩子,则可以在其集合更新时以类似的方式重新创建筛选器对象:

filter = {...filter, collection: [...filter.collection, myCollection]};

第一种方法我不能使用,因为我需要传递带有集合属性和元数据的fulle对象。第二种方法,在哪里应用它?我将其添加到我的答案中-您也可以完全重新创建过滤器对象。您必须在包含筛选器对象的组件中应用此模式,例如,在向其添加新筛选器或删除筛选器时。我可以共享我的设置服务,但我不知道在何处重新创建ArraI我知道您的想法,但我不知道如何在我的情况下应用此模式。您可以检查我的问题吗,我已添加我的服务