简体   繁体   中英

How to append components dynamically in angular?

Hi I have the following service which i want to use to append the components dynamically.

i am building a chat app where message components get added dynamically.

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);
  }
}

Could someone please help me how to use this service?

Suppose i have a message component, how to pass component to this service?

lets say you have a component you want to render

@Component(...)
export class MyComponent {
}

you should provide it as entryComponent to a module

@NgModule({
  declarations: [MyComponent],
  entryComponents: [MyComponent]
})
export class SomeModule {
}

and then from any place you can call

class Anything {
 constructor(private domService: DomService){}
 doRender(){ this.domService.appendComponentToBody(MyComponent);}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM