Angular: Using ViewChild and Input at the Same time, Side Effects or Best practice?

╄→гoц情女王★ 提交于 2020-03-12 06:46:32

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/60315005/angular-using-viewchild-and-input-at-the-same-time-side-effects-or-best-practi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!