如何在Angular的父类中调用子方法?

Posted

技术标签:

【中文标题】如何在Angular的父类中调用子方法?【英文标题】:How to call child method in parent class in Angular? 【发布时间】:2018-07-08 06:45:24 【问题描述】:

我的父类代码:

import  Child  from './child';

class Parent
     // onGateOpen(para1); how to access it here ? 

我的子类代码位于名为 child.ts 的单独文件中:

class Child extends parent
   onGateOpen(para1)
        // some code for opening the gate is here.
   

谢谢。

【问题讨论】:

angular website 上有很多关于此的文档 @Gab 你能放一些对我有帮助的链接吗? 老实说,快速谷歌搜索可以引导您找到答案。在 *** 上发布之前,您需要研究您的问题 Angular 2 - How to trigger a method on a child from the parent的可能重复 【参考方案1】:

有几种方法,您可以通过服务绑定它,或者直接将方法公开为子组件上的输出,或者可以在父组件上获取子组件的引用,然后从子实例调用该方法,或者有一个可观察的从父母传递给孩子,孩子会听。这是第一个例子:

class ChildComponent 
  constructor(private gateService: GateService) 
  ngOnInit() 
    this.gateService.openGate$.subscribe((params: any) => this.onGateOpen(params));
  
  private onGateOpen(params) 
  



class ParentComponent 
  constructor(private gateService: GateService) 
  openGate() 
    this.gateService.openGate('some param');
  


class GateService 
  openGate$: Subject<string> = new Subject();
  openGate(param) 
    this.openGate$.next(param);
  

阅读更多相关信息here。

【讨论】:

以上是关于如何在Angular的父类中调用子方法?的主要内容,如果未能解决你的问题,请参考以下文章