Angular Standalone Component
standalone component
是Angular 14的一个新特性,它可以让我们在不创建module的情况下创建一个component。注意:Directive
和Pipe
也可以是standalone的。
创建一个standalone component
组件代码如下:
1 | import { Component, OnInit } from '@angular/core'; |
standalone component和module的交互使用有如下两种情况。
standalone component引入其他module
如果standalone component需要引入其他module,那么需要在imports
属性中引入其他module,比如上面代码中引入的CommonModule
。
注意:只有standalone component才能引入其他module,普通的component(non-standalone component)不能引入其他module
。所以只有standalone component才能使用imports
属性。
如果你遇到如下报错,那么说明你在非standalone组件中使用了imports
属性,这是不允许的。
1 | error NG2010: 'imports' is only valid on a component that is standalone. |
这种情况经常发生在,ComponentA(非独立组件)想在template中使用ComponentB(独立组件),那么应该在ComponentA所在的module中的imports属性中引入ComponentB。
module引入standalone component
如果一个module要使用一个standalone component,那么不再
需要在declarations
属性中声明这个standalone component,只需要在imports
属性中引入这个standalone component所在的module即可。
1 | ({ |
lazy load module
在NgModel时代,我们可以使用loadChildren
来实现懒加载,比如下面的product module
:
1 | export const routes: Routes = [ |
Lazy load standalone component
在Angular 14中,我们可以使用loadComponent
来实现懒加载standalone component,比如下面的order component
:
1 | export const routes: Routes = [ |
summary
- lazy load module:
loadChildren
- lazy load standalone component:
loadComponent
Bootstrap standalone component
See here