What is the difference between @Output and Viewchild in Angular

Viewed 26

I have drop-down in child component and I want to use drop-down selected value in Parent component. I have two options do that first is by using @Output and second is by using @Viewchild. I have confuse which one to use. Which is the best way and why?

1 Answers

@Output create "custom events". So if in child you has

@Output()myEvent:EventEmitter<any>=new EventEmitter<any>()

Your parent can "listen" the event, and execute a function (defined in parent)

<app-child (myEvent)="myfunction($event)"></app-child>

With @ViewChild you has access to the child from parent (and to all the functions and public variables (in Angular all the variables are public by defect) of the child

Your parent

<app-child #child></app-child>

@ViewChild('child') child:ChildComponent

They are different. You choose @Output if you want "listen event", you use ViewChild if you want to get the variables or execute one function of the child. In the case of drop-down sounds that you want to know when change the dropdown (you want listen an event), so use @Output.

Related