Angular入口组件(entry component)和声明式组件的区别

转:
entry component 表示 angular 的入口组件。
它主要可以分为引导入口组件和路由到的入口组件。
可引导组件是一个入口组件,Angular 会在引导过程中把它加载到 DOM 中。 其它入口组件是在其它时机动态加载的,比如用路由器。
入口组件是在entryComponents 数组中声明的。
但是通常我们不需要显示的在entryComponents 数组中声明,因为angular足够聪明,它会自动的把bootStrap 中的组件以及路由器导航到的组件自动的加载到entryComponents 数组中去。虽然这种机制能适用大多数情况,但是如果是一些特殊的命令式的引导或者动态的加载某个组件(比如对话框组件),那么你必须主动的把这个组件声明到entryComponents 数组中去。

angular编译器会为那些可以从entryComponents 数组中取得的或者可以间接取得的组件生成生产环境的代码。因此,你可以只将必须使用的组件声明在entryComponents 数组中。
Angular的声明式组件和入口组件的区别体现在两者的加载方式不同。

  • 声明式组件是通过组件声明的selector加载

入口组件(entry component)是通过组件的类型动态加载

声明式组件

声明式组件会在模板里通过组件声明的selector加载组件。

示例

@Component({
  selector: 'a-cmp',
  template: `
  

这是A组件

  ` }) export class AComponent {}
@Component({
  selector: 'b-cmp',
  template: `
  

在B组件里内嵌A组件:

     ` }) export class BComponent {}

在BComponent的模板里,使用selector声明加载AComponent。入口组件(entry component)

入口组件是通过指定的组件类加载组件。

主要分为三类:

  1. 在@NgModule.bootstrap里声明的启动组件,如AppComponent。
  2. 在路由配置里引用的组件
  3. 其他通过编程使用组件类型加载的动态组件

启动组件

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent{}

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

在bootstrap里声明的AppComponent为启动组件。虽然我们会在index.html里使用组件的selector的位置,但是Angular并不是根据此selector来加载AppComponent。这是容易让人误解的地方。因为index.html不属于任何组件模板,Angular需要通过编程使用bootstrap里声明的AppComponent类型加载组件,而不是使用selector。

由于Angular动态加载AppComponent,所有AppComponent是一个入口组件。

路由配置引用的组件

@Component({
  selector: 'app-nav',
  template: `
  
  
  `
})
export class NavComponent {}

我们需要配置一个路由

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "user",
    component: UserComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Angular根据配置的路由,根据路由指定的组件类来加载组件,而不是通过组件的selector加载。

配置入口组件

在Angular里,对于入库组件需要在@NgModule.entryComponents里配置。

由于启动组件和路由配置里引用的组件都为入口组件,Angular会在编译时自动把这两种组件添加到@NgModule.entryComponents里。对于我们自己编写的动态组件需要手动添加到@NgModule.entryComponents里。

@NgModule({   declarations: [     AppComponent   ],   imports: [     BrowserModule,     BrowserAnimationsModule,     AppRoutingModule   ],   providers: [],   entryComponents:[DialogComponent],   declarations:[]   bootstrap: [AppComponent] }) export class AppModule { }

你可能感兴趣的:(angular)