您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Angular入口组件与声明式组件使用详解

2024/4/8 22:37:40发布24次查看
这次给大家带来angular入口组件与声明式组件使用详解,angular入口组件与声明式组件使用的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
组件是angular中很重要的一部分,下面这篇文章就来给大家介绍关于angular入口组件(entry component)与声明式组件的区别,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)
入口组件是通过指定的组件类加载组件。
主要分为三类:
在@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<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 { }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
css modules优雅模式使用
vue-cli多模块打包使用详解
以上就是angular入口组件与声明式组件使用详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product