5

When to use ViewChild, Input and Output? As one can achieve all the properties of class using ViewChild then why to use Input and Output.

In simple scenario Input and Output is best. But I have 4 to 5 levels deep hierarchies of component. In that case should I use ViewChild or to travel data to last component using Input and take back event to top component using Output?

How are they three impact performance of the application?

Ashish S
  • 638
  • 6
  • 14

2 Answers2

3

@ViewChild:
We can use viewchild to access the native element properties. ex: if i want to implement the click event whenever our component is rendered then i have to use @ViewChild.

@ViewCild('refDiv'): refDiv = ElementRef;

ngOnInit() {
   this.refDiv.nativeElement.click();
}

divClick() {
  console.log('div is clicked!!!');
}

HTML

<div #refDiv (click)="divClick()"> 
</div>

@Input If we have two component and both have the parent child relationship, And we want to pass the data from parent to child on that case we can use @Input.

@Output If we have two component and both have the parent child relationship, And we want to pass the data from the child to parent then on that case we can use @Output.

Yash Rami
  • 2,276
  • 1
  • 10
  • 16
  • Okay the used case is clear, but how would you define the performance. As most of the work can be easily done with ViewChild? If I have 100 components and I am using ViewChild everywhere, so will it affect the performance? – Ashish S Jun 13 '19 at 10:17
  • No there is no effect on performance bcs we are accessing the value when some event occurs and there are also no chances of memory leaks – Yash Rami Jun 13 '19 at 10:21
1

By parent child components I would use Input and Output. But by 2 levels and more I would use Services. And then you can write setter and getter methods. Everthing else is just hard to maintain and has a high chance for bugs

DEVolkan
  • 572
  • 5
  • 7