【问题标题】:How to call child method in parent class in Angular?如何在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 angular-components


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2016-12-22
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多