Angular动态创建组件之入口
2024-01-21 11:42:30
想要在 Angular 应用中创建动态组件,我们可以借助 Angular 提供的 API 和 CDK Portals 这两种方式。除此之外,我们还将探索与之相关的概念,例如 Angular 多级依赖注入和 ViewContainerRef。
Angular 动态创建组件
在 Angular 中,可以通过两种方式动态创建组件:
- 使用 Angular API
- 使用 CDK Portals
1. 使用 Angular API
Angular 提供了专门用于动态创建组件的 API,如下:
@Component({
selector: 'dynamic-component',
template: '<p>动态创建的组件</p>'
})
export class DynamicComponent {}
@Component({
selector: 'app-root',
template: `<button (click)="createComponent()">创建组件</button>
<div #container></div>`
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
createComponent() {
const componentRef = this.container.createComponent(DynamicComponent);
}
}
在代码中,我们首先定义了一个简单的动态组件 DynamicComponent
。然后在根组件 AppComponent
中,我们使用 ViewContainerRef
来创建和管理动态组件。当点击按钮时,我们将 DynamicComponent
实例动态添加到 AppComponent
的模板中。
2. 使用 CDK Portals
Angular CDK 提供了 Portals 服务,使我们能够以更加灵活的方式创建和管理动态组件。如下:
import { ComponentPortal, PortalInjector } from '@angular/cdk/portal';
@Component({
selector: 'dynamic-component',
template: '<p>动态创建的组件</p>'
})
export class DynamicComponent {}
@Component({
selector: 'app-root',
template: `<button (click)="createComponent()">创建组件</button>
<div #container></div>`
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
createComponent() {
const injector = new PortalInjector(this.container.injector, { data: { name: 'CDK Portals' } });
const portal = new ComponentPortal(DynamicComponent, null, injector);
this.container.createEmbeddedView(portal);
}
}
在上面的例子中,我们使用了 ComponentPortal
和 PortalInjector
来创建动态组件。我们还将数据传递给了动态组件,以便在组件中使用。
Angular 多级依赖注入
在 Angular 中,我们可以使用多级依赖注入来为动态创建的组件提供依赖项。多级依赖注入允许我们在创建组件时指定依赖项,以便在组件中使用。
@Component({
selector: 'dynamic-component',
template: '<p>动态创建的组件,使用了依赖注入</p>'
})
export class DynamicComponent {
constructor(private service: MyService) {}
}
@Component({
selector: 'app-root',
template: `<button (click)="createComponent()">创建组件</button>
<div #container></div>`
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
createComponent() {
const injector = new PortalInjector(this.container.injector, { data: { service: new MyService() } });
const portal = new ComponentPortal(DynamicComponent, null, injector);
this.container.createEmbeddedView(portal);
}
}
在代码中,我们使用 PortalInjector
为 DynamicComponent
提供了 MyService
依赖项。这使得我们可以在 DynamicComponent
中使用 MyService
。
Angular ViewContainerRef
ViewContainerRef
是一个 Angular 类,它允许我们在组件模板中动态创建和管理视图。在 Angular API 和 CDK Portals 两种方式中,我们都使用了 ViewContainerRef
来创建动态组件。
总结
在本文中,我们介绍了两种在 Angular 中创建动态组件的方式:Angular API 和 CDK Portals。我们还探讨了 Angular 多级依赖注入和 ViewContainerRef 等相关概念。通过本文,我们能够更好地理解和使用这些概念来创建动态组件。