这次给大家带来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)
入口组件是通过指定的组件类加载组件。
主要分为三类:
在@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 { }
登录后复制
相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!
推荐阅读:
怎样处理JS中双击和单击事件冲突问题
如何用vue写一个自定义组件
以上就是Angular入口组件与声明式组件案例对比的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2757085.html