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

编程知识 更新时间:2023-05-02 04:39:28

转:

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)

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

主要分为三类:

在@NgModule.bootstrap里声明的启动组件,如AppComponent。

在路由配置里引用的组件

其他通过编程使用组件类型加载的动态组件

启动组件

appponent.ts

@Component({

selector: 'app-root',

templateUrl: './appponent.html',

styleUrls: ['./appponent.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入口_Angular入口组件(entry component)和声明式组件的区别

本文发布于:2023-04-25 23:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/cc1e6cc43e29512a28ebcd74e7664dc4.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   入口   区别   声明   angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 103924文章数
  • 26194阅读数
  • 0评论数