Динамически создавать несколько экземпляров одного и того же компонента. - PullRequest
0 голосов
/ 12 мая 2018

Есть ли способ динамически создавать несколько экземпляров одного и того же компонента в angular?Я пробовал это с помощью componentFacory, но безуспешно.

1 Ответ

0 голосов
/ 12 мая 2018
private helloRef: ComponentRef<HelloComponent>;
private byeRef: ComponentRef<GoodbyeComponent>;
private helloCopyRef: ComponentRef<HelloComponent>;

@ViewChild('host', {read: ViewContainerRef}) theHost: ViewContainerRef;

constructor(private resolver: ComponentFactoryResolver, private injector: Injector) { }

ngOnInit(): void {
    let factory = this.resolver.resolveComponentFactory(HelloComponent);
    this.helloRef = factory.create(this.injector);
    this.helloCopyRef = factory.create(this.injector);

    factory = this.resolver.resolveComponentFactory(GoodbyeComponent);
    this.byeRef = factory.create(this.injector);
}

show(){
    this.theHost.detach();
    this.theHost.insert(this.helloRef.hostView);
    this.theHost.insert(this.byeRef.hostView);
    this.theHost.insert(this.helloCopyRef.hostView);
}

Проверьте эту ссылку для демонстрации: https://stackblitz.com/edit/angular-4aus6a

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...