[英]Angular child component variable not updating when called from parent component
[英]The Parent Variable is not updating in the child Component in Angular
我在父组件中有一个变量,如下所示:
父组件
export class ParentComponent {
variable = {};
varExample = false;
@ViewChild('child') child: ChildComponent;
someFunction () {
this.variable['id'] = {};
for (let i = 0; i < 10; i++) {
this.variable['id'][i] = i*2;
}
this.varExample = true;
}
otherFunction () { // called when i click a button
this.someFunction ();
console.log(this.child.variable); // {}
console.log(this.child.varExample); // true
this.child.initVars();
}
}
父 HTML
<app-child #child [variable]="variable" [varExample]="varExample"></app-child>
子组件
export class ChildComponent {
@Input() variable: any;
@Input() varExample: boolean;
initVars() {
console.log(this.variable); // {}
console.log(this.varExample); // true
}
}
这只是我实现的一个例子,是的,我有所有的导入。
在那些console.log(this.variable)
中,我得到了一个空的 object ( {}
),但 varExample 仍然可以正常工作。 为什么孩子的variable
总是空的,Angular 没有检测到这种类型的对象( {}
)的变化?
有人能帮我吗?
varExample
,您重新分配它的值this.varExample =...
。 但是对于this.variable
,只有它的内容被改变了。 当底层参考没有改变时,Angular 不会检测到它的变化。 您可以使用@user2846469 中的解决方案,也可以使用扩展语法来调整值和内联引用。家长
someFunction() {
this.variable["id"] = {};
for (let i = 0; i < 10; i++) {
this.variable = {
...this.variable,
id: {
...this.variable["id"],
[i]: i * 2
}
};
}
this.varExample = true;
}
@ViewChild
触发另一个组件的 function 是不优雅的。 相反,您可以在子组件中使用OnChanges
挂钩。 只要在任何@Input
变量中检测到更改,就会触发它。孩子
import { Component, Input, OnChanges, SimpleChanges } from "@angular/core";
export class ChildComponent implements OnChanges {
@Input() variable: any;
@Input() varExample: boolean;
ngOnChanges(changes: SimpleChanges) {
if (changes.variable && changes.variable.currentValue) {
console.log(changes.variable.currentValue);
}
}
}
工作示例: Stackblitz
是的,我也有这个问题。 试试这样:
someFunction() {
const tmp = {};
tmp['id'] = {};
for (let i = 0; i < 10; i++) {
tmp['id'][i] = i * 2;
}
this.variable = tmp;
this.varExample = true;
}
即使用临时 object 然后将 object 分配给您的变量。 我认为问题在于 Angular 的变更检测。 如果您不分配它,则在这种情况下不会检测到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.