什么是动静组件?
动静组件是指在运行时依据条件或用户操作动静加载并渲染的组件。这种技术容许应用程序依据须要动静地切换和加载不同的组件。举例来说,当用户在应用程序中进行了特定的操作,比方点击按钮或者抉择了某个选项,你能够依据这些操作加载不同的组件,而不用在应用程序初始化时将所有组件都加载进来。也就是说组件的模板不会永远是固定的。利用可能会须要在运行期间加载一些新的组件
实现动静组件
在 Angular 中实现动静组件通常波及以下几个步骤:
创立动静组件:须要创立要动静加载的组件。这些组件与一般组件一样,但通常会用于展现特定的内容或性能。
创立容器组件:接下来,你须要创立一个容器组件,用于动静加载其余组件。这个容器组件应该蕴含一个指令或组件,用来标记动静加载组件的地位。
通过组件工厂加载组件:应用 Angular 提供的ComponentFactoryResolver 和 ViewContainerRef,你能够在容器组件中动静加载组件。首先,解析要加载的组件的工厂,而后应用工厂创立组件并将其增加到视图容器中。
Angular中应用动静组件时罕用的API
1.ViewContainerRef:
用于治理动静加载的组件的容器。它提供了一种将动态创建的组件插入到特定地位的办法,并提供了对插入组件的拜访和管制。
容器治理:ViewContainerRef 能够视作一个容器,用于动静加载和治理组件。
动静组件加载:通过 ViewContainerRef,能够在容器中动静地创立组件实例,并将其增加到容器中。
清空容器:ViewContainerRef 还提供了一个 clear() 办法,用于清空容器中的所有内容,能够在须要时用来移除已加载的组件。
2.ComponentFactoryResolver:
容许在运行时动静加载组件,而不是在编译时将所有组件都蕴含在模板中。
@ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;// 解析 MyComponent 的工厂const componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyComponent); // 创立 MyComponent 的实例,并将其增加到视图容器中const componentRef = this.dynamicComponentContainer.createComponent(componentFactory);
应用示例
创立两个不同的动态组件:
import { Component } from '@angular/core';@Component({ selector: 'app-dynamic', template: '<p>组件一</p>',})export class DynamicComponent {}
import { Component } from '@angular/core';@Component({ selector: 'app-dynamic-two', template: '<p>动静加载组件二</p>',})export class DynamicTwoComponent {}
创立容器组件
export class AppComponent { @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef; constructor(private componentFactoryResolver: ComponentFactoryResolver) {} loadComponent1() { this.loadComponent(DynamicComponent); } loadComponent2() { this.loadComponent(DynamicTwoComponent); } loadComponent(component: any) { this.dynamicComponentContainer.clear(); const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component); this.dynamicComponentContainer.createComponent(componentFactory); }}
<!--app.component.html--><div #dynamicComponentContainer></div><button (click)="loadComponent1()">加载组件一</button><button (click)="loadComponent2()">加载组件二</button>
动静切换
ngOnInit(): void { setInterval(() => { this.loadComponent1(); setTimeout(() => { this.loadComponent2(); }, 1000); }, 2000); }
![上传中...]()
总结
动静组件就像是你在玩积木,但这些积木是在你玩的时候才从盒子里拿进去的,而不是一开始就都摆在桌子上。在 Angular 中,动静组件就像是这些积木,你能够依据你的须要,在利用程序运行时动静地加载它们。
参考
https://angular.cn/guide/dynamic-component-loader