Как добавить компоненты динамически в угловых? - PullRequest
0 голосов
/ 10 октября 2019

Привет У меня есть следующий сервис, который я хочу использовать для динамического добавления компонентов.

Я создаю приложение чата, в котором компоненты сообщений добавляются динамически.

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

Может ли кто-нибудь помочь мне, как пользоваться этой услугой?

Предположим, у меня есть компонент сообщений, как передать компонент этой службе?

1 Ответ

1 голос
/ 10 октября 2019

Допустим, у вас есть компонент, который вы хотите визуализировать

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

вы должны предоставить его как entryComponent для модуля

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

, а затем из любого места, куда вы можете позвонить

class Anything {
 constructor(private domService: DomService){}
 doRender(){ this.domService.appendComponentToBody(MyComponent);}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...