嗨,我想使用以下服务来动态添加组件。
我正在构建一个聊天应用程序,其中动态添加了消息组件。
import {
Injectable,
Injector,
ComponentFactoryResolver,
EmbeddedViewRef,
ApplicationRef
} from '@angular/core';
@Injectable()
export class DomService {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector
) { }
appendComponentToBody(component: any) {
// 1. Create a component reference from the component
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(this.injector);
// 2. Attach component to the appRef so that it's inside the ng component tree
this.appRef.attachView(componentRef.hostView);
// 3. Get DOM element from component
const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
// 4. Append DOM element to the body
document.body.appendChild(domElem);
// 5. Wait some time and remove it from the component tree and from the DOM
setTimeout(() => {
this.appRef.detachView(componentRef.hostView);
componentRef.destroy();
}, 3000);
}
}
有人可以帮助我如何使用此服务吗?
假设我有一个消息组件,如何将组件传递给该服务?
答案 0 :(得分:1)
让我们说您要渲染一个组件
@Component(...)
export class MyComponent {
}
您应将其作为模块的entryComponent提供
@NgModule({
declarations: [MyComponent],
entryComponents: [MyComponent]
})
export class SomeModule {
}
然后在任何可以打电话的地方
class Anything {
constructor(private domService: DomService){}
doRender(){ this.domService.appendComponentToBody(MyComponent);}
}