是通过ViewContainerRef的createComponent方法创建组件实例,并使用ComponentRef的instance属性来调用组件的方法。
具体步骤如下:
constructor(private viewContainerRef: ViewContainerRef) { }
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
const componentRef = this.viewContainerRef.createComponent(componentFactory);
const childComponentInstance = componentRef.instance;
childComponentInstance.doSomething();
完整的示例代码如下:
import { Component, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<ng-template #container></ng-template>
<button (click)="createComponent()">Create Component</button>
`,
})
export class ParentComponent {
constructor(private viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) { }
createComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
const componentRef = this.viewContainerRef.createComponent(componentFactory);
const childComponentInstance = componentRef.instance;
childComponentInstance.doSomething();
}
}
这样,就可以使用cmpRef调用动态创建的组件angular的方法。请注意,这只是一个示例,实际应用中可能需要根据具体情况进行适当的调整。
领取专属 10元无门槛券
手把手带您无忧上云