7

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.

2
  • No, because I am passing some data through arguments from the child component. So in order to pass it to the higher component, I am using eventEmmiter. Commented Nov 14, 2017 at 16:31
  • Output and Input will be able to help you achieve this. Or EventEmitter like the answer below Commented Nov 14, 2017 at 21:39

1 Answer 1

12

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

That answers my question. Thank you
Thank you for the answer. What if we need send similar event from parent to child??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.