【问题标题】:Invoke Child method(and pass data) from parent, Child will be dynamically loaded component(router-outlet or lazy loaded child) in angular从父级调用子级方法(并传递数据),子级将以角度动态加载组件(路由器出口或延迟加载的子级)
【发布时间】:2021-11-18 02:31:40
【问题描述】:

子组件是延迟加载的组件,所以

父母

“child.childMethod()”

这不起作用,请有人帮我从父组件调用子方法以及如何在子组件和父组件之间传递数据 这就像主布局和不同的子组件场景。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    根据我对 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
          })
    }
    

    【讨论】:

    • 谢谢拉斐尔,让我试试这个
    • @Aja 成功了吗,您需要更多帮助吗?
    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多