Angular中的动态组件加载
看了Angular官网Hero教程中的动态组件一节,然后还看了一篇讲的不错的文章,结合自己的理解,总结Angular动态组件加载如下: import { Component,OnInit } from '@angular/core'; @Component({ selector: 'dy1-component',template: `<div>Dynamic Component 1</div>` }) export class DY1Component implements OnInit { constructor() { } ngOnInit() { } } 动态组件2: import { Component,OnInit } from '@angular/core'; @Component({ selector: 'dy2-component',template: `<div>Dynamic Component 2</div>` }) export class DY2Component implements OnInit { constructor() { } ngOnInit() { } } 定义好的组件必须要在module里的declarations和entryComponents中声明: @NgModule({ declarations: [ AppComponent,DY1Component,DY2Component ],entryComponents: [ DY1Component,DY2Component ] imports: [ BrowserModule ],providers: [],bootstrap: [AppComponent] }) export class AppModule { } Angular中凡是要用到的组件都要在declarations中声明这好理解,但是为什么要在entryComponents里面也要去声明呢?别忘了我们的组件是动态组件,这意味着angular根本不知道我们在运行时要加载哪些动态组件,所以angular在编译阶段不会为这些动态组件进行实例化,但是当运行时我们需要它的时候,angular得知道啊,这里就告诉angular这些是动态组件,需要在运行的时候给我临时创建。其实在entryComponents里声明的组件,angular都会创建一个工厂(ComponentFactory)并且存储在ComponentFactoryResolver(相当于一个工厂集合)中,然后在需要的时候由工厂去创建这些动态组件,后面会详细说明。 @Component({ selector: 'dynamic-com',template: ` <section> <button (click)="addComponent()">Add Component</button> <button (click)="stopSwitch()">Stop</button> <section #dmroom></section> </section> ` }) export class DY1ComponentComponent implements OnInit { @ViewChild('dmroom',{ read: ViewContainerRef }) dmRoom: ViewContainerRef; currentIndex: number = -1; interval: any; comps: any = [DY1Component,DY2Component]; constructor(private cfr: ComponentFactoryResolver) { } addComponent() { this.interval = setInterval(() => { this.currentIndex = (this.currentIndex + 1) % this.comps.length; let comp = this.comps[this.currentIndex]; let com = this.cfr.resolveComponentFactory(comp); this.dmRoom.clear(); this.dmRoom.createComponent(com); },1000); } stopSwitch() { clearInterval(this.interval); } ngOnInit() { } ngOnDestroy() { clearInterval(this.interval); } } 我们这个组件用一个定时器去不断循环加载我们定义的两个动态组件,用@ViewChild获取模板中的<section>节点作为加载的容器,其中{read: ContainerRef}是说把这个节点当作ContainerRef进行解释,因为ContainerRef可以去挂载组件。我们依赖注入了ComponentFactoryResolver,用它来获取动态组件的工厂,然后ContainerRef调用createComponent完成两件事:1.利用动态组件的工厂创建出动态组件的实例,2. 把动态组件的实例挂载到ContainerRef中。至此提一个问题,为什么Angular实现动态组件要用工厂模式而不直接new呢?从上面可以看到,其实动态组件不仅仅是需要创建它的实例,还需要考虑如何去加载动态组件到它的宿主元素上,甚至还有其他的一些额外操作,所以如果我们仅仅是new一个组件,那么只是组件的一个很小的部分,或者说只是初始化了组件中的‘一些变量,而组件的很多其他内容,包括很多DOM操作都没有去做,而利用组件工厂,angular恰恰帮我们去做了这些事情,屏蔽了诸如DOM操作的相关内容,所以我们要用工厂模式去解决动态组件的问题。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |