kittencup / angular2-ama-cn

angular2 随便问
692 stars 101 forks source link

ng2中component中引用其他component需要在ngModule中指定declarations? #247

Closed 0x1111 closed 7 years ago

0x1111 commented 7 years ago

之前,应该是ng2 RC5或者其他版本之前是支持@Component中使用directives来引用其它component的,那我只需要知道怎么使用这个component即可,不需要关注这个component依赖了哪些组件。

现在,component中引用其他component,都必须在@NgModule的declarations来指定依赖的component,那我就必须要知道所有的依赖关系,感觉复杂了很多。

举例: 我的Componet中引用一个TableComponent,结果TableComponent中又依赖了PaginationComponent。

原本(component.ts): @Component { directives: [TableComponent] }

现在(app.module.ts): @NgModule{ declarations: [TableComponent, PaginationComponent, ....(可能还有其它的依赖项)] }

ng2小白一枚,求各位指导我的理解是不是对的?对于我这种场景是否有更好的解决办法?

hstarorg commented 7 years ago

其实现在更简单了,你需要在NgModule中导出所有的组件。那么另外的模块只需要import你的组件Module,就可以直接使用组件标签了。

0x1111 commented 7 years ago

多谢。 新看了SharedModule的概念,这个应该是更推荐的方式了。

-- 但想到另外一个问题,SharedModule会把我所有的component都导出,可能会存在只有部分component被引用的情况,另外的component被加载,但是一直未使用,岂不是占用js空间?

hstarorg commented 7 years ago

@0x1111 我觉得没有真正引用,就不会被实例化。

0x1111 commented 7 years ago

所有的Component都在SharedModule中已经export了,如果webpack等打包工具还去检查component是否被引用,感觉成本有点高了。

不过这里影响应不大,以后有时间了可以再研究下,多谢了。