您可以通过使用ComponentFactoryResolver动态创建组件然后将它们注入ViewContainerRef来完成您要实现的目标.动态执行此操作的一种方法是将组件的类作为函数的参数传递,该函数将创建并注入组件.
见下面的例子:
import {
Component,
ComponentFactoryResolver, Type,
ViewChild,
ViewContainerRef
} from '@angular/core';
// Example component (can be any component e.g. app-header app-section)
import { DraggableComponent } from './components/draggable/draggable.component';
@Component({
selector: 'app-root',
template: `
Add
Remove
`
})
export class AppComponent {
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
// Keep track of list of generated components for removal purposes
components = [];
// Expose class so that it can be used in the template
draggableComponentClass = DraggableComponent;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
addComponent(componentClass: Type) {
// Create component dynamically inside the ng-template
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);
const component = this.container.createComponent(componentFactory);
// Push the component so that we can keep track of which components are created
this.components.push(component);
}
removeComponent(componentClass: Type) {
// Find the component
const component = this.components.find((component) => component.instance instanceof componentClass);
const componentIndex = this.components.indexOf(component);
if (componentIndex !== -1) {
// Remove component from both view and array
this.container.remove(this.container.indexOf(component));
this.components.splice(componentIndex, 1);
}
}
}
笔记:
>如果您希望以后更容易删除组件,可以在局部变量中跟踪它们,请参阅this.components.或者,您可以遍历ViewContainerRef中的所有元素.
>您必须将组件注册为条目组件.在模块定义中,将组件注册为entryComponent(entryComponents:[DraggableComponent]).