ViewChild与Input/Ouput-Angular最佳做法 [英] ViewChild vs Input/Ouput - Angular Best Practices

查看:76
本文介绍了ViewChild与Input/Ouput-Angular最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,在几乎所有我们指定了组件@Input s/@Output s的情况下,我们都可以没有任何@Input s/@Output s,而是使用@ViewChild来访问组件属性直接地.例如,考虑寻呼机的以下两种可能的API:

It seems to me that in almost all cases where we specify component @Inputs/@Outputs we could alternatively not have any @Inputs/@Outputs but instead use @ViewChild to access component properties directly. For example, consider these two possible APIs for a pager:

选项1:将当前页面和总页面公开为@Input s,为下一个/上一个页面请求设置事件发射器(@Output s).

Option 1: Expose current page and total pages as @Inputs, make event emitters (@Outputs) for the next/previous page requests.

<pager 
    [currentPage]="..." 
    [totalPages]="..." 
    (requestsNextPage$)="..." 
    (requestsPreviousPage$)="..."
></pager>

选项2:为当前页面和总页面设置简单属性,为下一个/上一个页面请求设置可观察对象/主题,并通过@ViewChild公开.

Option 2: Make simple properties for current page and total pages, make observables/subjects for next/previous page requests and expose via @ViewChild.

<pager></pager>

@ViewChild(PagerComponent)
pager: PagerComponent

pager.currentPage = ...
pager.totalPages = ...

pager.requestsNextPage$.subscribe(...)
pager.requestsPreviousPage$.subscribe(...)

我的问题是,如果在大多数情况下这两种选择都同样可行,那么什么是首选/最佳实践?为什么?

My question is, if both of these options are equally possible in most cases, what is the preferred/best practice and why?

推荐答案

您描述的两种情况并不相同.

The two situations you describe are not equivalent.

情况A:

<child [property]="value"></child>

子组件将使用属性=值"呈现,并且每当值"更改时,子组件的视图就会更新(因为输入属性已更改).

The child component will be rendered with "property = value" and whenever "value" changes, the child component's view will be updated (because an input property changed).

情况B:

<child></child>

child.property = value;

子组件使用属性=值"呈现(取决于此代码在生命周期中的运行时间),并且进一步的更改不会反映在子组件的视图中.

The child component is rendered with "property = value" (depending when in the lifecycle this code runs) and further changes will NOT be reflected in the child component's view.

如果您只是设置一个永不更改的初始值,则可能这两种情况是等效的.但是,这不太可能是您想要做的. Angular在重用组件方面非常积极,其使用的标准之一就是@Input属性.我遇到了这样的麻烦:由于这种行为,组件被重用而不是删除并重新创建,因此理解和调试它会非常令人沮丧.

If you're just setting an initial value that never changes, then it may be possible for these two situations to be equivalent. However, that's unlikely to be what you want to do. Angular is very aggressive about re-using components, and one of the criteria it uses is the @Input properties. I have run into trouble where a component was reused instead of deleted and re-created due to this behavior, and it can be very frustrating to understand and debug.

这篇关于ViewChild与Input/Ouput-Angular最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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