【发布时间】:2020-06-15 03:00:25
【问题描述】:
好的,标题可能有点混乱。我的子组件在它自己的模块中,并且正在使用父组件不可用的服务。
我想在单击按钮时更改子组件中的一些值,并且正在搞乱并设置这样的东西。
@Component({
selector: 'app-parent-component'
template: `
<button (click)="refreshData()" />
<app-child-component> </app-child-component>
`
})
export class ParentComponent{
refreshData() {
ChildComponent.runRefresh()
}
}
@Component({
selector: 'app-child-component'
template: ``
})
export class ChildComponent{
static runRefresh() {
console.log('refreshing')
// Do things involving data on a service scoped to this component/module
}
}
我很好奇这种方法是否存在固有的问题?有没有更好的方法来解决这个问题。我熟悉检查 NgOnChanges 事件的变化。
我想我想要做的是在子组件内部调用一个方法,该方法使用来自父组件的作用域服务上的子组件资源。
编辑:也知道使用@ViewChild 并且不使子组件方法静态。也许这是唯一“正确”的方式?
【问题讨论】:
-
我能想到的只有一个,如果你有多个组件实例,你要刷新哪个组件?我想我宁愿选择有自己的方式通过@Input setter 或其他方式触发刷新的组件。
-
@IngeOlaisen 刷新更多的是刷新数据并调用api。实际上并没有刷新浏览器中的任何内容。我知道我可以使用 ViewChild 并在
上添加参考。只是在寻找新的方法 -
为什么
runRefresh是静态的? -
@ConnorsFan 这只是静态的,因为我正在试验。我喜欢你的解决方案。谢谢!
标签: angular