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

查看:143
本文介绍了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?

当前具有父级"和子级"组件.

Currently have Parent and Child component.

要求:

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)还需要应用输入,但是请在此处查看资源, ViewChild vs Input/Ouput-Angular最佳做法

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

ViewChild将不会显示子组件View数据的更改,这些更改来自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这两个选项来提取这两个好处,想知道以后是否会导致错误吗?如果Native 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天全站免登陆