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

本文介绍了Angular中的入口组件(entry component)与声明式组件的区别。入口组件包括引导入口和路由到的入口,主要在`entryComponents`数组中声明,而声明式组件通过模板内的selector加载。Angular自动处理大部分入口组件的声明,但在某些特殊情况下需要手动添加到`entryComponents`。文章还详细解析了启动组件、路由配置引用的组件和动态组件的加载方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转:

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。

在路由配置里引用的组件

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

启动组件

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 { }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值