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

前端 未结 1 609
故里飘歌
故里飘歌 2020-12-22 12: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 h

相关标签:
1条回答
  • 2020-12-22 13:32

    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

    0 讨论(0)
提交回复
热议问题