abhilash reddy
abhilash reddy

Reputation: 1586

How to call an event in parent component from child component?

I have implemented tabs in where i have a form & a button in tab1. I have an event in parent component which makes the current tab deactive and the next tab active. How to call the event in parent component from the child component?

  gotosecondtab(){
this.firsttabactive=false;
this.secondtabactive=true;
}

This is the event in parent component...I want to run this event from child component

onSubmit(): void {  
console.log('you submitted value: ', this.myForm.value); 
//How to call the parent event here
}

I want to run gotosecondtab() event when i execute onSubmit() event...Somebody help me please

Upvotes: 3

Views: 2732

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

You can create a custom event in your child component

@Component({
  selector: 'child',
  (...)
})
export class ChildComponent {
  @Output() myevent: EventEmitter;

  constructor() {
    this.myevent = new EventEmitter();
  }

  onSubmit(): void {  
    console.log('you submitted value: ', this.myForm.value); 
    this.myevent.emit();
  }
}

and register on it from the parent component:

@Component({
  template: `
    <child (myevent)="gotosecondtab()"></child>
  `,
   directives: [ ChildComponent ]
  (...)
})
export class ParentComponent {
  (...)

  gotosecondtab() {
  }
}

Hope it helps, Thierry

Upvotes: 6

Related Questions