gpt4 book ai didi

javascript - Angular:使用 @Input() 传递数据

转载 作者:行者123 更新时间:2023-12-01 01:47:59 25 4
gpt4 key购买 nike

我有三个组件——组件 A、组件 B 和组件 C。组件 A 包装组件 B。组件 B 包装组件 C。如果我在每个组件中使用 @Input(),将更改根组件传递中的选项通过嵌套组件到组件C?见下文:

<component-a [options]="options">
<component-b [options]="options">
<component-c [options]="options">
</component-c>
</component-b>
</component-a>

我问这个问题是因为当应用程序的根组件中的选项发生更改时,我需要对每个嵌套组件进行一些过滤。但是,我注意到第三方组件的一些异常行为似乎没有收到 options ?在回答了这个问题的第一部分后,我可以进一步详细说明。

我相信这个问题的答案是"is"。这是第二部分。如何更新<ng-select>当组件按如下方式换行时:

<component-a [options]="options">
<component-b [options]="options">
<ng-select [items]="options" [(ngModel)]="selectedOption">
</ng-select>
</component-b>
</component-a>

<ng-select>的文档说如下:

Change Detection

Ng-select component implements OnPush change detection which means the dirty checking checks for immutable data types. That means if you do object mutations like:

this.items.push({id: 1, name: 'New item'})

Component will not detect a change. Instead you need to do:

this.items = [...this.items, {id: 1, name: 'New item'}];

This will cause the component to detect the change and update. Some might have concerns that this is a pricey operation, however, it is much more performant than running ngDoCheck and constantly diffing the array.

那么我如何确保对 options 进行更改反射(reflect)在 <ng-select>

最佳答案

我有一个解决方法。由于您的 options 是一个对象,因此 Angular 不会检测该对象的更改。您需要更改对象的引用,以便 Angular 解析更改

下面是有效的代码,您的更改检测将按预期进行

this.options = Object.assign({},this.options)

The above code will change the reference of the object due to which change detection will be triggered

关于javascript - Angular:使用 @Input() 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com