[英]Angular2 access to the methods in child component from parent
我的問題是關於從父組件訪問childerns組件方法的方法。 我找到了使用下面的例子描述的解決方案,但我擔心我可能是錯誤的,而不是'angular2 right'的方式。
比如我們有孩子:
@Component({ ... })
export class Modal {
...
open() {
...
}
}
和父母:
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'方法,是否有最簡單,更直接的方法?
有很多方法可以做到,
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 ,從父本身可以訪問子方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.