|
|
|
import { ApplicationRef, ComponentFactoryResolver, ComponentRef, EmbeddedViewRef, Injectable, Injector } from '@angular/core';
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class SearchService {
|
|
|
|
constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef, private injector: Injector,) { }
|
|
|
|
|
|
|
|
//angular 动态添加组件
|
|
|
|
appendComponentToBody<T>(component: any): ComponentRef<T> {
|
|
|
|
//create a component reference
|
|
|
|
const componentRef = this.componentFactoryResolver.resolveComponentFactory(component).create(this.injector);
|
|
|
|
// attach component to the appRef so that so that it will be dirty checked.
|
|
|
|
this.applicationRef.attachView(componentRef.hostView);
|
|
|
|
|
|
|
|
// get DOM element from component
|
|
|
|
const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
|
|
|
|
|
|
|
|
document.body.appendChild(domElem);
|
|
|
|
|
|
|
|
return componentRef as ComponentRef<T>;
|
|
|
|
}
|
|
|
|
|
|
|
|
//删除组件
|
|
|
|
removeComponentFromBody(componentRef: ComponentRef<any>) {
|
|
|
|
this.applicationRef.detachView(componentRef.hostView);
|
|
|
|
componentRef.destroy();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|