Reputation: 1124
I have two methods in a service that both hit different controllers for searching my database. I'd like to make a shared child component which will be used in two different places, however I need each instance to be able to specifically call one of the service methods. For example, these are my methods:
// SERVICE
searchOne(search: string){
// do some searching in Controller 1
}
searchTwo(search: string){
// do some searching in Controller 2
}
With my shared child component having a similar method to hit the service:
// CHILD COMPONENT
@Input(Function) func: Function;
componentSearch(search: string){
this.func(search);
}
However, this doesn't seem to work when trying to pass a function from a parent like so:
// PARENT COMPONENT
func = this.service.searchOne;
constructor(private service: Service){}
// PARENT COMPONENT.HTML
<app-child-component [func]="func"></app-child-component>
How do I pass access or reference of the service functions into my child component?
Upvotes: 1
Views: 117
Reputation: 568
I have created a working Stackblitz for your code here
Few corrections in your code:
Parent component:
export class AppComponent {
name = 'Angular';
func;
constructor(private service: AppService){
this.func = this.service.searchOne;
}
}
Child Component
@Input() func: Function;
componentSearch(search: string){
this.func(search);
}
Upvotes: 1