簡體   English   中英

角度2:如何從另一個組件調用方法

[英]Angular 2: How to call a method from another component

我的html模板中有一個調用方法的按鈕,但是在其自己的組件中找不到該方法。 在另一個組件中找到它。 我該怎么辦?

HTML模板:

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

可以在dialog-box.component.ts找到showConfirmation()方法。

在我的showConfirmation() ,我有一個jQuery,它允許查看Semantic-UI模式

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

Angular文檔中有一整章旨在回答這個問題。 您可以在這里找到它: https : //angular.io/guide/component-interaction

關鍵選項是:

  • 使用輸入綁定將數據從父級傳遞到子級
  • 用設置器截取輸入屬性的更改
  • 使用ngOnChanges()攔截輸入屬性更改
  • 家長聽孩子活動
  • 父母通過局部變量與孩子互動
  • 父調用@ViewChild()
  • 組件通過服務進行通信

如本文中所提到的,除最后一個外,所有其他組件都假定這兩個組件具有父/子關系,這意味着一個組件嵌套在另一個組件內。

在親子關系中,一種方法是讓父母偵聽有關孩子的事件。 子項需要輸出: @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

您可以從角芯使用viewChild裝飾器

 @ViewChild(dialogComponent)
  private localDialog: dialogComponent

showConfirmation() {

this.localDialog.showConfirmation();
}

您可以在這里獲得更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM