首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在angular中动态添加组件?

如何在angular中动态添加组件?
EN

Stack Overflow用户
提问于 2019-10-10 19:56:05
回答 1查看 126关注 0票数 0

您好,我有以下服务,我想使用它来动态追加组件。

我正在构建一个聊天应用程序,其中消息组件是动态添加的。

代码语言:javascript
运行
复制
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);
  }
}

有没有人可以教我如何使用这项服务?

假设我有一个消息组件,如何将该组件传递给该服务?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-10 20:28:38

假设您有一个要呈现的组件

代码语言:javascript
运行
复制
@Component(...)
export class MyComponent {
}

您应该将其作为entryComponent提供给模块

代码语言:javascript
运行
复制
@NgModule({
  declarations: [MyComponent],
  entryComponents: [MyComponent]
})
export class SomeModule {
}

然后从任何你能呼叫的地方

代码语言:javascript
运行
复制
class Anything {
 constructor(private domService: DomService){}
 doRender(){ this.domService.appendComponentToBody(MyComponent);}
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58322365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档