这次给大家带来Angular入口组件与声明式组件案例对比,Angular入口组件与声明式组件案例使用的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
组件是Angular中很重要的一部分,下面这篇文章就来给大家介绍关于Angular入口组件(entry component)与声明式组件的区别,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)
入口组件是通过指定的组件类加载组件。
主要分为三类:
启动组件
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 { }相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:










