Satyajit Shetye
Satyajit Shetye

Reputation: 100

Passing data from Parent Component to Child Component

I am new to Angular. I want to pass data from Parent Component to Child Component. One way to achieve this is by using @input() Decorator. Today I came across another method. That is, getting the local reference of Child Component using @ViewChild and assigning the property to its instance. Is this a correct way to pass data?

Upvotes: 1

Views: 2176

Answers (2)

Generally, if you don't absolutely need it, you should prefer using the @Input() decorator and pass values to the child component using it.

@ViewChild reference is often used in cases when you need to call some component's methods and not just update the property value. It gives you more flexibility.

Also, in terms of change detection, using @Input is more efficient. Especially if you use ChangeDetectionStrategy.OnPush. This way Angular knows that the only time it needs to detect changes is when the @Input changes.

Putting change detection aside, it's simply not a common practice to update the properties using ViewChild() and such code can be less comprehensible and robust.

In cases when you simply need to pass the value from the parent to child component you should definitely use @Input.

Upvotes: 1

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Both ways are valid. However, using @Input makes it more clear it's an input. This might not something you need, but could be very usefull to other developers.

Using @ViewChild you get a reference to the component. Of course you can set a property, but why would you if you have an @Input. But you could call a method using the @ViewChild.

Though it is perfectly valid to use it, I try to avoid it as much as possibler because it's not always very intuitive.

Upvotes: 0

Related Questions