gpt4 book ai didi

使用数组输入属性时,父项中的 Angular2 更改未反射(reflect)在子项中

转载 作者:太空狗 更新时间:2023-10-29 18:27:09 25 4
gpt4 key购买 nike

假设我们将组件 A 作为父组件,将组件 B 作为子组件。 child 有一个由 parent 提供的输入what_is_x。像这样:

对于家长:

@Component({
selector: 'cmp-A',
directives: [ComponentB],
template: `<cmp-B [what-is-x]="x"></cmp-B>`
})
export ComponentA {
public x: any = [1, 2, 3];
constructor() {
setTimeout(() => this.x.push(10), 2000);
}
}

对于 child :

// component B with input what_is_x
@Component({
selector: 'cmp-B',
template: `{{what_is_x}}`
})
export ComponentB {
@Input('what-is-x') public what_is_x: any;
}

我的问题是,如果父级通过某种方式更改了 x,子级是否会更新为新值?根据开发指南中的“组件通信”章节(尚未发布);它应该!但它没有为我更新,到目前为止尝试了所有测试版 (0,1,2)

最佳答案

更新:自 beta.16 起,{{what_is_x}} 现在将在 View 中更新,即使数组引用未更改。另见 {{myArray}} now updates in the view as of beta.16 .


原答案:

The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs. -- doCheck() API doc

正如@Eric 在评论中提到的,您在 View 中看不到任何更新的原因是因为您只绑定(bind)到模板中的数组 - {{what_is_x}} - 并且由于数组 reference 在我们修改数组(例如,使用 push())时不会更改,因此更改检测不会检测到任何更改。

如果这确实是您的用例,请按照@Eric 的建议并返回一个不同的数组,然后更改检测将注意到数组引用已更改。

通常,我们的模板绑定(bind)到数组的各个项目。例如,

<div *ngFor="#item of what_is_x">{{item}}</div>

由于为数组的每个项目创建了一个绑定(bind),如果我们添加、删除或修改一个项目,更改检测会注意到(我们不需要返回不同的数组)。

为了调试,如果您改为使用 {{what_is_x | json}},您还会在数组更改时看到 View 更新。 (这是因为 JsonPipe 是有状态的,这会导致 Angular 变更检测在每个变更检测周期对其进行评估。)

关于使用数组输入属性时,父项中的 Angular2 更改未反射(reflect)在子项中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35096695/

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