簡體   English   中英

如何在不同的組件中調用方法

[英]How to call the method in the different component

如何使用 ViewChild 調用不同組件中的方法?

我在餅圖組件中創建了一個方法,並嘗試從應用程序組件 usinf ViewChild 訪問該方法。

這是我的 piechart.component.ts

export class PiechartComponent {
  constructor() { }
  pie(){
console.log("Hello World")
}
}

這是我的 app.component.ts

export class AppComponent {
 @ViewChild(PiechartComponent) piechart:PiechartComponent;
 constructor(){ }
 pieChart(){ 
 this.piechart.pie();
}
}

這是我的 app.component.html

<button (click)="pieChart()">Pie Chart</button>

當我點擊一個按鈕時,我應該得到輸出為“Hello world”。 但我收到以下錯誤。 “類型錯誤:無法讀取未定義的屬性‘餅’”

您需要在父組件模板中添加子組件

<pie-chart ></pie-chart>
<button (click)="pieChart()">Pie Chart</button>

演示

暫無
暫無

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

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