【发布时间】:2021-11-18 02:31:40
【问题描述】:
子组件是延迟加载的组件,所以
父母
“child.childMethod()”
这不起作用,请有人帮我从父组件调用子方法以及如何在子组件和父组件之间传递数据 这就像主布局和不同的子组件场景。
【问题讨论】:
标签: angular typescript
子组件是延迟加载的组件,所以
“child.childMethod()”
这不起作用,请有人帮我从父组件调用子方法以及如何在子组件和父组件之间传递数据 这就像主布局和不同的子组件场景。
【问题讨论】:
标签: angular typescript
根据我对 Angular 的理解,以这种方式延迟加载组件时无法使用 child.childMethod(),因为父级不知道它将加载什么。
如果您尝试多次触发childMethod(),则可以选择使用服务。
它将在parent 中提供,然后您就可以在child 中使用它。
然后您可以通过从parentService 订阅提供程序来触发childMethod()
// parent.module.ts
providers: [
ParentService
]
// parent.service.ts
triggerChildMethod$: BehaviorSubject<boolean> = new BehaviorSubject(null)
// parent.component.ts
constructor(private _parentService: ParentService) {}
childMethod() {
this._parentService.next(true);
}
// child.component.ts
constructor(private _parentService: ParentService) {}
ngOnInit() {
this._parentService
.pipe(
filter((event) => (typeof event === "boolean" ? true : false)), // Avoid triggered on instantiating
takeUntil(this._unsubscribeAll), // Do not forget to unsubscribe
)
.subscribe((value) => {
this.childMethod() // Here you are
})
}
【讨论】: