Angular 2:如何从另一个组件调用方法

时间:2017-06-16 01:24:02

标签: angular methods angular2-template angular2-directives

我的html模板中有一个调用方法的按钮,但是在自己的组件中找不到此方法。它在另一个组件中找到。我该怎么办?

HTML模板:

<button class="ui button basic medium" (click)="showConfirmation()">Delete</button>

showConfirmation()

中找到dialog-box.component.ts方法

在我的showConfirmation()中,我有一个允许查看Semantic-UI模式的jQuery

showConfirmation(show: boolean){
      $('.ui.small.modal').modal('show');
}

3 个答案:

答案 0 :(得分:4)

Angular文档中有一整章旨在回答这个问题。您可以在此处找到它:https://angular.io/guide/component-interaction

关键选项是:

  • 使用输入绑定将数据从父级传递给子级
  • 使用setter拦截输入属性更改
  • 使用ngOnChanges()
  • 拦截输入属性更改
  • 父级侦听子事件
  • 父级通过本地变量
  • 与子级进行交互
  • Parent调用@ViewChild()
  • 组件通过服务进行通信

正如在这些文本中所提到的,除了最后一个假设两个组件都有父/子关系,这意味着其中一个组件嵌套在另一个组件中。

答案 1 :(得分:2)

在亲子关系中,一种方法是让父母听取孩子的事件。孩子需要一个输出:@Output() onShowConfirmation = new EventEmitter<boolean>();和一个发出事件的函数,如下所示:

showConfirmation(show: boolean) {
    this.onShowConfirmation.emit(show);
    this.confirmationShown = true;
}

然后,在父模板中,将父组件中的函数绑定到子组件上的输出:

<confirmation-widget>
    (onShowConfirmation)="onShowConfirmation($event)">
</confirmation-widget>

这只是下面链接的文档中示例的修改版本。

或者,您可以使用服务来协调这两个组件。这真的取决于他们的关系。在这里查看Angular文档,看看给出配置的最佳方法是什么:

https://angular.io/guide/component-interaction#component-interaction

答案 2 :(得分:0)

你可以使用angular core

中的viewChild装饰器
 @ViewChild(dialogComponent)
  private localDialog: dialogComponent

showConfirmation() {

this.localDialog.showConfirmation();
}

您可以获得更多详细信息here

相关问题