Reputation:
Would there be any errors or collision if using ViewChild
and Input
at the same time? Or is it recommended practice in general?
Currently have Parent and Child component.
Requirements:
a) Parent needs to tell child component to conduct many things: mark form as touched, update values, manipulate the DOM, remove validators, etc. Things which are harder with @Input().
b) Also needs to apply input, however looking at resource here, ViewChild vs Input/Ouput - Angular Best Practices
ViewChild will not display child component View data changes, from ongoing inputs with NgOnChanges(). However, using @Input() will render changes in the Input/parameter.
So if using both options, ViewChild And Input to extract both benefits, wondering if it may cause errors later? Will Native Angular 8 face any channel communication issues if it has these two ways of communicating with child?
Other Resource :
angular's @input vs viewchild for sending data from parent to child component
Upvotes: 2
Views: 1672
Reputation: 58019
The link you indicate is a bit old. In my opinion, the use of viewChild is usefull when we want to use a method or function of the child(*), or change his aspect. For control a variable or a FormGroup or formControl my best bet is use @Input.
Remember that, when we pass an object to a child in a Input, there are an unique object, so parent and children has the value when any change happens -in children or in parent-, e.g. if we pass a FormGroup, you can mark as touched, remove/add validators, use setValue... from parent or form children. About @Input is true that if you has a "input fixed" -you pass a variable that not change- ,as
<child greet="Hello word"></child>
You should use @Attribute in constructor, NOT input
constructor(@Attribute('greet') greet){}
(*)you can use a input with a setter, but in this case I like much more use viewChild or a variable reference
Upvotes: 3