我的问题是关于从父组件访问子组件方法的方式。我找到了使用以下示例描述的解决方案,但我担心这可能是我做错了,而不是“angular2 正确”的方式。
例如我们有 child :
@Component({ ... })
export class Modal {
...
open() {
...
}
}
和 parent :
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();
}
}
在 editor.html 中:
<button (click)="open()">Open Editor</button>
<modal #editModal>{{ bindModal(editModal) }}
Here is my editor body in modal (popup) window
...
</modal>
这是从 Editor 组件访问 Modal 组件内的 open()
方法的解决方案。这有点棘手。问题是:有没有不使用'bindModal'方法的最简单直接的方法?
最佳答案
有很多方法可以做到,
@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();
}
}
其他方法是使用 #localVariable您可以从父级本身访问子方法。
关于methods - Angular2 从父组件访问子组件中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279595/