【问题标题】:Accessing parent component method from child从子访问父组件方法
【发布时间】:2022-01-02 15:46:27
【问题描述】:
我正在开发一个 Angular 应用程序。我在父组件中有一个返回响应的方法。
parentComponent.ts:
myMethod(id) {
//API call and return response on the basis of id
}
这个父组件有很多子组件。我想从子组件调用这个方法。从子组件调用此方法时,我将传递一个 ID,该 ID 将依次调用 API 并在子组件中给出响应。如何从子组件调用此父组件方法并在子组件中获取响应。我该怎么做?
【问题讨论】:
标签:
angular
angular8
angular9
angular10
【解决方案1】:
这是从子方法调用父方法的简单示例:
Parentcomponent.html
<app-child-component (parentFun)="parentFun()" ></app-child-component>
Parentcomponent.ts
parentFun(){
alert("parent component function.");
}
childcomponent.html
<button (click)="onClick()">
click me, to Call parent component function.
</button>
childcomponent.ts
export class ChildComponentComponent implements OnInit {
@Output("parentFun") parentFun: EventEmitter<any> = new EventEmitter();
constructor() { }
ngOnInit() {
}
onClick(){
this.parentFun.emit();
}
}