簡體   English   中英

如何在投影的任意角度子組件中訪問方法 <ng-content> ?

[英]How to access methods in arbitrary Angular child component projected with <ng-content>?

我正在使用Angular Material進行對話框,它將是一個父組件(包含對話框的頁眉和頁腳),然后可以使用<ng-content>/ng-content>投射任意子組件(對話框內容)。

dialog.component.html:

<h1 mat-dialog-title>Title</h1>
<mat-dialog-content>
  <ng-content></ng-content>
</mat-dialog-content>
<mat-dialog-actions>
  <button mat-icon-button (click)="submit()">
    <mat-icon>save</mat-icon>
  </button>
</mat-dialog-actions>

任意對話框的content.component.html

<dialog>
  <!-- Dialog content here -->
</dialog>

我想做的是從對話框的save()方法中調用任意對話框內容的save()方法,因此我需要從父組件中獲取對任意組件的引用。 我嘗試使用@ContentChild,但無法使其正常工作,因為直到運行時,我才知道哪個組件將成為對話框內容。

您可以在對話框組件上使用事件發射器在組件之間進行通信。

將其添加到您的dialog.ts中:

@Output() onSubmit = new EventEmitter();

submit() {
  // do whatever you want
  this.onSubmit.next();
}

然后在您的任意組件html中:

<dialog (onSubmit)="save()">
  <!-- Dialog content here -->
</dialog>

其中save()是您的組件保存功能

共享服務將是一個更全面的解決方案,但這適用於此用例。

暫無
暫無

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

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