methods - Angular2 从父组件访问子组件中的方法

标签 methods angular components parent children

我的问题是关于从父组件访问子组件方法的方式。我找到了使用以下示例描述的解决方案,但我担心这可能是我做错了,而不是“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/

相关文章:

Angular 2 导入另一个 "sibling"模块会注入(inject)错误的组件

java - 通过返回值更改字段与通过在方法中引用字段来更改字段?

java - 如何删除传递给 Java 方法的对象?

javascript - 无法在 React 中绑定(bind)处理程序

typescript - Angular 2 RC2 单选按钮绑定(bind)损坏

Angular2 - 指令在未在同一模块中声明时不起作用

c# - 用于创建具有合并功能的电子邮件模板的好库

java - 如何访问其他方法中定义的变量

C# 创建像 PHP 一样的可调用对象

angular - 一行和一列的唯一单选按钮