Я хотел бы добавить динамический компонент - PullRequest
0 голосов
/ 04 июля 2019

Я хотел бы добавить динамический компонент из службы.Мой компонент BubbleComponent.

import { BubbleComponent } from '@app/component/bubble';
import {SiplecService} from '@app/service/siplec.service';

@NgModule({
  imports: [
    FormsModule,
    CommonModule,
    NgbModule,
    RouterModule.forChild(HomeRoutes),
  ],
  declarations: [HomeComponent, BasketComponent, BubbleComponent],
  entryComponents: [ BubbleComponent ],
  providers: [ SiplecService ]
})
export class HomeModule {}

В моем сервисе:

 setRootViewContainerRef(viewContainerRef: any) {
        this.rootViewContainer = viewContainerRef;
    }
    addDynamicComponent() {
        const factory = this.factoryResolver
            .resolveComponentFactory(BubbleComponent);
        const component = factory
            .create(this.rootViewContainer.parentInjector);
        this.rootViewContainer.insert(component.hostView);
    }

Я получаю следующую ошибку:

Ошибка: не найдена фабрика компонентов дляBubbleComponent.Вы добавили его в @ NgModule.entryComponents?at noComponentFactoryError (core.js: 7409)

1 Ответ

0 голосов
/ 04 июля 2019

Можете ли вы попробовать ниже код, чтобы увидеть, работает ли он

@ViewChild("dynamicContainer", { read: ViewContainerRef }) container: ViewContainerRef;
componentRef: ComponentRef<BubbleComponent>;
constructor(private resolver: ComponentFactoryResolver) {}

createComponent(type) {
    //Clear the container.
    this.container.clear();
    //Create a factory for component.
    const factory = this.resolver.resolveComponentFactory(BubbleComponent);
    //Create a component using the factory
    this.componentRef = this.container.createComponent(factory);
}

Также убедитесь, что вы импортируете в объявления тоже

@NgModule({
  declarations: [
    BubbleComponent
  ],
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...