3 changed files with 33 additions and 3 deletions
@ -0,0 +1,30 @@
|
||||
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(component: any) { |
||||
//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; |
||||
} |
||||
|
||||
removeComponentFromBody(componentRef: ComponentRef < any > ) { |
||||
this.applicationRef.detachView(componentRef.hostView); |
||||
componentRef.destroy(); |
||||
} |
||||
|
||||
} |
Loading…
Reference in new issue