Angular2访问来自父级的子组件中的方法

Kam*_*ski 3 methods components children parent angular

我的问题是关于从父组件访问childerns组件方法的方法.我找到了使用下面的例子描述的解决方案,但我担心我可能是错误的,而不是'angular2 right'的方式.

比如我们有孩子:

@Component({ ... })
export class Modal {
    ...
    open() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

和父母:

import { Modal } from '../common';
...
@Component({
  selector: 'editor',
  directives: [ Modal ],
  templateUrl: './editor.html',
  ...
})
export class Editor {

    _modal = null;

    ...

    bindModal(modal) { this._modal=modal; }

    open() {
        this._modal.open();
    }
}
Run Code Online (Sandbox Code Playgroud)

在editor.html中:

<button (click)="open()">Open Editor</button>

<modal #editModal>{{ bindModal(editModal) }}
    Here is my editor body in modal (popup) window
    ...
</modal>
Run Code Online (Sandbox Code Playgroud)

这是从Editor组件访问open()Modal组件内部方法的解决方案.这有点棘手.问题是:如果没有使用'bindModal'方法,是否有最简单,更直接的方法?

mic*_*yks 5

有很多方法可以做到,

@ViewChild

import  {ViewChild} from '@angular/core';
import { Modal } from '../common';
...
@Component({
  selector: 'editor',
  directives: [ Modal ],
  templateUrl: './editor.html',
  ...
})
export class Editor {
 @ViewChild(Modal) md:Modal;

 Open()
 {
    this.md.open();
 }

}
Run Code Online (Sandbox Code Playgroud)

其他方法是使用#localVariable,从父本身可以访问子方法.

  • 然后,您可以使用#LocalVariable,检查给定答案的链接或您可以使用`exportAs`的链接. (2认同)