Reputation: 728
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?
Upvotes: 4
Views: 9341
Reputation: 2327
@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
.
Upvotes: 2
Reputation: 592
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
Upvotes: 0