createComponent方法接受ComponentFactoty类,创建后返回的ComponentRef类,可以获取到组件实例(instance),控制组件销毁。 大致思路是这样的,先获取到了HovertipComponent组件对于的componentFactory,监听鼠标移入事件,在触发事件时,通过ViewContainerRef类来创建组件,存下返回的组件componentRef(获取实例,销毁组件时需要用到),向组...
privateelementRef:ElementRef,privateinjector:Injector){this.component=this.componentFactoryResolver.resolveComponentFactory(AComponent).create(this.injector);}ngAfterViewInit(){lethost=document.createElement("div");host.appendChild((this.component.hostViewasany).rootNodes[0]);this.elementRef.nativeElement...
let factory = this.cfr.resolveComponentFactory(CustomComponent); let componentRef = this.viewContainerRef.createComponent(factory); componentRef.instance.data = 'hello'; setTimeout(() => { componentRef.instance.data = 'bye'; }, 2000); } }...
{}createComponent(componentType:any){constcomponentFactory=this.componentFactoryResolver.resolveComponentFactory(componentType);constcomponentRef=this.container.createComponent(componentFactory);// 可以在这里设置组件的属性或调用组件的方法componentRef.instance.someProperty='some value';componentRef.instanc...
在我们定义createComponent()方法前,我们需要注入ComponentFactoryResolver服务对象。该ComponentFactoryResolver服务对象中,提供了一个很重要的方法 -resolveComponentFactory(),该方法接收一个组件类作为参数,并返回ComponentFactory。 ComponentFactoryResolver 抽象类:
this.tooltipsComponentRef = this.viewContainerRef.createComponent(TooltipsComponent); 创建完毕后,我们需要对ToolTips设置一些属性,例如要展示的文字,位置: private setTooltipComponentProperties() { if (!this.tooltipsComponentRef) { return; } this.tooltipsComponentRef.instance.text = this.tooltipText; ...
const childComponentRef = this.container.createComponent(childComponentFactory); // 可以通过childComponentRef来访问或操作子组件 } } 可以通过childComponentRef来访问或操作子组件。例如,可以使用instance属性来获取子组件实例,并调用其方法或访问其属性。例如: ...
One thing to notice here is that, after we call destroy(), the this.component instance is still there, it won't be removed. If you do want to clean it you can use 'onDestroy()' method to clean it: this.component.onDestroy(() =>{ ...
declarations: [ TestAlertComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TestAlertComponent); component = fixture.componentInstance; alertElement = fixture.debugElement.query(By.directive(AlertComponent)).nativeElement; ...
使用api创建组件,现根据组件类型创建一个ComponentFactory对象,然后调用viewContainer的createComponent创建组件 使用componentRef.instance获取创建的组件实例,这里用来设置组件的task属性值 其它 ViewContainerRef除了createComponent方法外还有一个createEmbeddedView方法,用于创建模板 ...