关于angular:Angular入口组件entry-component和声明式组件的区别

2次阅读

共计 2645 个字符,预计需要花费 7 分钟才能阅读完成。

转:
entry component 示意 angular 的入口组件。
它次要能够分为疏导入口组件和路由到的入口组件。
可疏导组件是一个入口组件,Angular 会在疏导过程中把它加载到 DOM 中。其它入口组件是在其它机会动静加载的,比方用路由器。
入口组件是在 entryComponents 数组中申明的。
然而通常咱们不须要显示的在 entryComponents 数组中申明,因为 angular 足够聪慧,它会主动的把 bootStrap 中的组件以及路由器导航到的组件主动的加载到 entryComponents 数组中去。尽管这种机制能实用大多数状况,然而如果是一些非凡的命令式的疏导或者动静的加载某个组件(比方对话框组件),那么你必须被动的把这个组件申明到 entryComponents 数组中去。

angular 编译器会为那些能够从 entryComponents 数组中获得的或者能够间接获得的组件生成生产环境的代码。因而,你能够只将必须应用的组件申明在 entryComponents 数组中。
Angular 的申明式组件和入口组件的区别体现在两者的加载形式不同。

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

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

申明式组件

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

示例

@Component({
  selector: 'a-cmp',
  template: `
  <p> 这是 A 组件 </p>
  `
})
export class AComponent {}
@Component({
  selector: 'b-cmp',
  template: `
  <p> 在 B 组件里内嵌 A 组件:</p>
  <a-cmp></a-cmp>
  `
})
export class BComponent {}

在 BComponent 的模板里,应用 selector<a-cmp></a-cmp> 申明加载 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<app-root></app-root> 的地位,然而 Angular 并不是依据此 selector 来加载 AppComponent。这是容易让人误会的中央。因为 index.html 不属于任何组件模板,Angular 须要通过编程应用 bootstrap 里申明的 AppComponent 类型加载组件,而不是应用 selector。

因为 Angular 动静加载 AppComponent,所有 AppComponent 是一个入口组件。

路由配置援用的组件

@Component({
  selector: 'app-nav',
  template: `
  <nav>
    <a  routerLink="/home" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive"> 首页 </a>
    <a routerLink="/users" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive"> 用户 </a>
  </nav>
  <router-outlet></router-outlet>
  `
})
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 {}

正文完
 0