0%

angular-standalone-component

Angular Standalone Component

standalone component是Angular 14的一个新特性,它可以让我们在不创建module的情况下创建一个component。注意:DirectivePipe也可以是standalone的。

创建一个standalone component

组件代码如下:

1
2
3
4
5
6
7
8
9
10
11
import { Component, OnInit } from '@angular/core';
@Component({
standalone: true, // 添加这一句,表示这是一个standalone component。
imports: [CommonModule],
selector: 'lifecycle-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.less'],
})
export class OrderComponent{
constructor() {}
}

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
2
3
4
5
6
7
8
9
10
11
12
13
@NgModule({
declarations: [
AppComponent,
// OrderComponent, // no need to declare standalone component here
],
imports: [
BrowserModule,
OrderComponent, // imports standalone component here
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

lazy load module

在NgModel时代,我们可以使用loadChildren来实现懒加载,比如下面的product module

1
2
3
4
5
6
export const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'product', loadChildren: () => import('./product/product.module').then(m => m.ProductModule)},
{path: 'about', component: AboutComponent},
{path: '**', component: NotFoundComponent},
];

Lazy load standalone component

在Angular 14中,我们可以使用loadComponent来实现懒加载standalone component,比如下面的order component

1
2
3
4
5
6
export const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'order', loadComponent: () => import('./order/order.component').then(m => m.OrderComponent)},
{path: 'about', component: AboutComponent},
{path: '**', component: NotFoundComponent},
];

summary

  • lazy load module: loadChildren
  • lazy load standalone component: loadComponent

Bootstrap standalone component

See here

References:

Angular standalone component