使用Angular2启动项目,我想知道你们中是否有人知道如何区分组件和子组件.我们如何决定以下架构的决定:
>元素何时应由组件表示?什么时候开始使用子组件?
>何时选择通过组件之间的服务进行通信?何时选择输入和输出指令?
>什么应该被视为一个模块而不是一个组件?
这是一个模糊的问题,因为一切都没有黄金法则.
- When does an element should be represented by a component ? when start using subcomponent ?
什么是组件?如果我们查看字典:更大整体的一部分或元素Angular中组件的概念是它们封装了所有逻辑,允许您在整个应用程序中重用它们.经验法则T-DRY(试着干),不要重复自己,如果你在几个组件上继续使用相同的逻辑,也许你可以将它提取到单个组件中并重新使用该组件.此外,它是一种减少html标记的好方法,例如查看堆栈溢出我们可以有答案/问题组件,标记对于两者都是相同的.但是在这个组件中,我们可能会有一些子组件,比如投票组件,配置文件组件,标签组件.
- When to choose to communicate via services between components ? when
to choose Input and Output directives ?
这个很简单,当你的组件只用作直接子节点而父节点负责提供逻辑或数据时,你只使用输入和输出.为什么?如果您有一条直接指向组件的路线,则无法输入和输出.另一个原因是,如果您的组件是深嵌套的孙子,您不希望继续通过组件传递输出/输入,这太麻烦了.
- what should be considered a module rather than a component ?
我建议你也阅读官方Angular 2 style guide,有条款app structure & modules基本上我的想法是创建每个功能的模块,或者如果你有一个简单的应用程序每个网址.以下是该部分的引用:
Do create an Angular module for all distinct features in an
application (e.g. Heroes feature).
Do place the feature module in the same named folder as the feature
area (.e.g app/heroes).
Do name the feature module file reflecting the name of the feature
area and folder (e.g. app/heroes/heroes.module.ts)
Do name the feature module symbol reflecting the name of the feature
area,folder,and file (e.g. app/heroes/heroes.module.ts defines
HeroesModule)
Why? A feature module can expose or hide its implementation from other
modules.
Why? A feature module identifies distinct sets of related components
that comprise the feature area.
Why? A feature module can easily be routed to both eagerly and lazily.
Why? A feature module defines clear boundaries between specific
functionality and other application features.
Why? A feature module helps clarify and make it easier to assign
development responsibilities to different teams.
Why? A feature module can easily be isolated for testing.