Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 generic click event in child component

Tags:

angular

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.

like image 497
Josh Walton Avatar asked Nov 14 '17 16:11

Josh Walton


1 Answers

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);
}
like image 86
Dmitry Grinko Avatar answered Sep 20 '22 02:09

Dmitry Grinko