如何在不同的组件中调用方法

时间:2019-01-04 11:25:51

标签: angular typescript

如何使用ViewChild在不同组件中调用方法?

我已经在Piechart组件中创建了一个方法,并尝试从应用程序组件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”。但是我得到以下错误。 “ TypeError:无法读取未定义的属性'pie'”

1 个答案:

答案 0 :(得分:1)

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

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

Demo