【问题标题】:Angular 2: How to call a method from another componentAngular 2:如何从另一个组件调用方法
【发布时间】:2017-06-16 01:24:02
【问题描述】:

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

HTML 模板:

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

showConfirmation()方法见dialog-box.component.ts

在我的showConfirmation() 中,我有一个 jQuery,它允许查看语义 UI 模式

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

【问题讨论】:

    标签: angular methods angular2-template angular2-directives


    【解决方案1】:

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

    关键选项是:

    • 使用输入绑定将数据从父级传递给子级
    • 使用 setter 拦截输入属性更改
    • 使用 ngOnChanges() 拦截输入属性更改
    • 家长监听子事件
    • 父母通过局部变量与孩子互动
    • 父母调用@ViewChild()
    • 组件通过服务进行通信

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

    【讨论】:

      【解决方案2】:

      在父子关系中,一种方法是让父级监听子级的事件。孩子需要一个输出:@Output() onShowConfirmation = new EventEmitter&lt;boolean&gt;(); 和一个在其上发出事件的函数,如下所示:

      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

      【讨论】:

      • 有没有办法让我通过服务打开一个模态?因为它不会读取 showConfirmation() 方法
      • 我实际上不认为您应该提供服务来协调它们,除非您在应用程序的多个部分或组件中有删除按钮。如果您可以制作一个 plunker 或您的问题示例,我很乐意帮助您修复您的实际代码。事实上,如果您只需要一个简单的确认框,我建议您查看 github.com/toverux/ngsweetalert2 之类的内容。
      【解决方案3】:

      您可以使用角度核心的 viewChild 装饰器

       @ViewChild(dialogComponent)
        private localDialog: dialogComponent
      
      showConfirmation() {
      
      this.localDialog.showConfirmation();
      }
      

      您可以了解更多详情here

      【讨论】:

      • 我应该把这个放在哪里?在当前组件中?
      • 它说“找不到名称“ViewChild””
      • 你可以从 import { AfterViewInit, ViewChild } from '@angular/core' 中导入
      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2018-07-07
      • 2017-05-19
      • 2018-04-14
      • 1970-01-01
      • 2018-05-06
      相关资源
      最近更新 更多