angular - 更改检测后角度子组件未更新
问题描述
也许我从一开始就有错误的设置,但是我遇到了一个问题,@Input
即在父变量更改后子组件装饰器没有更新。我的问题是父母的变量实际上正在从父母继承的另一个孩子的组件中得到更新。
子视图组件
@Component({
selector: 'sub-view',
templateUrl: './sub-view.component.html',
styleUrls: ['./sub-view.component.scss']
})
export class SubViewComponent {
@Input() links;
...
}
父组件
@Component({
selector: 'parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
roleLinks:any;
constructor() {}
...
}
父视图
<sub-view
[links]="roleLinks"
></sub-view>
子组件 #1
@Component({
selector: 'child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.scss']
})
export class Child1Component extends ParentComponent {
constructor() {
super();
this.roleLinks = [
{key:'a',val:'A'},
{key:'b',val:'B'}
];
}
...
}
我有Child1Component extends ParentComponent
,因为我的想法是我会有一个Child2
,Child3
等等。每个孩子都会有很多共享的组件Parent
所以SubView
will 只需要绑定到Parent
然后每个Child
Component 就可以拥有它自己的links
但是,我无法links
在查看其他 SO Q/A 中获得更新SubView
,我尝试了以下方法:
- 添加
ChangeDetectionStrategy.OnPush
到SubView
detectChanges()
从添加ChangeDetectorRef
到SubView
markForCheck()
从添加ChangeDetectorRef
到SubView
他们都没有工作。links
总是undefined
在里面SubView
,即使我可以看到当它在内部Child
发生变化时,变化实际上正在下降,Parent
但SubView
只是没有检测到变化
值得注意的是,我将每个Child
组件都嵌套<router-outlet>
在Parent
Component 中。
-App
<router-outlet>
+Page1
+Page2
-Parent
+SubView
<router-outlet>
+Child1
+Child2
+...
+OtherSubView
StackBlitz 示例
解决方案
所以,我认为问题在于您没有roleLinks
在父组件中分配属性,而是在子组件中(从不使用它)。
如果您有以下 parentComponent 模板
<childComponent [links]="roleLinks></childComponent>
然后roleLinks
会从父组件分配给子组件。roleLinks
基于类的继承与在原始父项上分配属性无关。
相反,您需要直接分配此属性,或者,如果您需要在父子之间共享状态,请使用您需要的数据创建一个角度服务并将其注入两者。
推荐阅读
- javascript - 使用 jsZIP 下载多个 pdfmake 文件
- nginx - 无法启动高性能 Web 服务器和反向代理服务器
- reactive-programming - 从 ServerWebExchange Spring 云网关读取请求正文
- python - 如何从数据流管道中的 PubSub 子目录中读取
- node.js - 在 Heroku Nodemon 上部署时未安装
- java - 无法在 Android 应用程序中使用形态指纹扫描仪设备捕获指纹
- python-3.x - 如何将列条目从日期转换为二进制(0 或 1)?
- python - 如何将变量从 PHP 传递到 Python 并返回?
- python - 安装 JupyterLab 时出现 Build Wheel 错误
- karate - 空手道框架:在运行加特林测试时,我们可以配置获取黄瓜报告吗