Angular:同时使用 ViewChild 和 Input,副作用还是最佳实践? [英] Angular: Using ViewChild and Input at the Same time, Side Effects or Best practice?

查看:20
本文介绍了Angular:同时使用 ViewChild 和 Input,副作用还是最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时使用ViewChildInput会不会有错误或者冲突?还是一般来说是推荐的做法?

Would there be any errors or collision if using ViewChild and Input at the same time? Or is it recommended practice in general?

目前有父子组件.

要求:

a) 父组件需要告诉子组件执行许多操作:将表单标记为已触摸、更新值、操作 DOM、删除验证器等.@Input() 更难处理的事情.

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) 也需要应用输入,但是在这里查看资源,ViewChildvs 输入/输出 - Angular 最佳实践

b) Also needs to apply input, however looking at resource here, ViewChild vs Input/Ouput - Angular Best Practices

ViewChild 不会显示来自 NgOnChanges() 正在进行的输入的子组件视图数据更改.但是,使用@Input() 将呈现输入/参数中的更改.

ViewChild will not display child component View data changes, from ongoing inputs with NgOnChanges(). However, using @Input() will render changes in the Input/parameter.

所以如果同时使用ViewChild和Input这两个选项来提取这两个好处,想知道以后会不会出错?如果原生 Angular 8 有这两种与孩子沟通的方式,它会面临任何渠道沟通问题吗?

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?

其他资源:

angular 的 @input 与 viewchild用于从父组件向子组件发送数据

推荐答案

您指出的链接有点旧.在我看来,当我们想要使用 child(*) 的方法或函数,或者改变他的方面时,使用 viewChild 很有用.对于控制变量或 FormGroup 或 formControl,我最好的选择是使用 @Input.

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.

请记住,当我们将一个对象传递给 Input 中的子项时,有一个唯一的对象,因此当任何更改发生时,父项和子项都具有值 - 在子项中或在父项中 - 例如如果我们传递一个 FormGroup,您可以标记为已触摸、删除/添加验证器、使用 setValue... 从父级或表单子级.关于@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>

你应该在构造函数中使用@Attribute,而不是输入

You should use @Attribute in constructor, NOT input

constructor(@Attribute('greet') greet){}

(*)你可以使用带有 setter 的输入,但在这种情况下,我更喜欢使用 viewChild 或变量引用

(*)you can use a input with a setter, but in this case I like much more use viewChild or a variable reference

这篇关于Angular:同时使用 ViewChild 和 Input,副作用还是最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆