There is a child component which is used in many pages of an angular web app. The child component has a (click)
event which calls a function. Each page that consist of this child component is calling a different function with different parameters on click event.
How can I make this (click)
event generic or dynamic that it calls the different function if the parent is different?
// In one component
(click)="saveData(types, functions)"
// On another component
(click)="showFunctions(index, areas, types)"
Using a single child component in multiple pages with different click event, how we can do this?
Thank you in advance.
Child:
<button type="button" (click)="onMyClick()">Click<button>
@Output() myClick = new EventEmitter();
onMyClick() {
this.myClick.emit();
}
Parent:
<my-child-cmp (myClick)="firstFunction()"></my-child-cmp>
firstFunction() {
// whatever
}
Parent2:
<my-child-cmp (myClick)="secondFunction()"></my-child-cmp>
secondFunction() {
// whatever
}
Hope it helps. Let me know if you need more details.
By the way if you need to send some data from child to your parent you can do smth like this:
Child:
<button type="button" (click)="onMyClick()">Click<button>
@Output() myClick = new EventEmitter();
onMyClick() {
this.myClick.emit(something);
}
Parent:
<my-child-cmp (myClick)="firstFunction($event)"></my-child-cmp>
firstFunction(event: Event) {
console.log(event); // You will see something here))
}
UPDATE:
If we need send data from parent to child
Parent
data: any;
ngOnInit() {
this.data = 'hello world';
}
<app-child [settings]="data"></app-child>
Child:
@Input() settings: any;
ngOnInit() {
console.log(this.settings);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With