Как скопировать представление из одной коллекции viewContainerRef в другую в angular4
Я пытаюсь загрузить несколько компонентов динамически, и только один из них виден одновременно. По сути, я создаю приложение, которое может иметь 100 или более компонентов, и я хочу динамически загружать подмножество этих компонентов во время выполнения в мое приложение. Я хочу одновременно просматривать только один из компонентов, но я хочу, чтобы каждый загруженный компонент оставался в DOM, чтобы пользователи могли редактировать на каждой вкладке и не терять изменения при смене вкладок. Я пытаюсь реализовать это, используя динамическую загрузку компонентов и абстрактный класс ViewComponentRef. Поскольку я хочу, чтобы все загруженные компоненты оставались в DOM до тех пор, пока я не удалю их, я создал два компонента контейнера и планирую скрыть один из них. Второй компонент контейнера будет содержать только загруженный компонент, который я хочу видеть. Я попытался сделать это, используя метод get() в основной коллекции и метод insert() в выбранной коллекции. Код работает без ошибок, но он не делает то, что я ожидал. Он не копирует фактическое содержимое компонента (т. Е. HTML) из основной коллекции в выбранную коллекцию. Как скопировать представления из одной коллекции в другую, и существует ли другой способ отображения только подмножества динамически загружаемых компонентов.
Машинопись
import { Component, Input, Output, EventEmitter, ComponentFactoryResolver, AfterViewInit, OnDestroy, ViewChild,Type, ViewContainerRef } from '@angular/core';
import { AppletContainer } from '../appletContainer/appletContainer.component';
import { AppletCollection } from '../appletCollection/appletCollection.component';
import { AdComponent } from '../ad.component';
import { TestComponent } from '../test.component';
export class AdItem {
constructor(public component: Type<any>, public data: any) {}
}
@Component({
selector: 'applet-frame',
templateUrl: '/NetworkDesigner2/views/app/appletFrame/appletFrame.component.html',
styleUrls: ['NetworkDesigner2/views/app/appletFrame/appletFrame.component.css'],
entryComponents:[TestComponent]
})
export class AppletFrame implements AfterViewInit, OnDestroy {
items: AdItem[] = [];
@Input() inputControlStructure:any;
@Output() updateControlStructure = new EventEmitter<any>();
currentIndex: number = 0;
counter:number = 0;
@ViewChild(AppletContainer) adHost: AppletContainer;
@ViewChild(AppletCollection) master: AppletCollection;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
let newItem = new AdItem(TestComponent,{component:'sample manual component',description:'sample manaual component'})
this.items.push(newItem);
}
ngAfterViewInit(){
}
ngOnDestroy(){}
loadComponent(){
// Identify the current target component to load
let adItem = this.items[this.currentIndex];
// Create the component Factory object for the target component
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
// Declare a reference to the viewContainerRef object for the 'master' collection. This is the ng-template that will be hidden
let viewContainerRef1 = this.adHost.viewContainerRef;
// Declare a reference to the viewContainerRef object for the 'select' collection. This is the collection that will show the selected component
let viewContainerRef2 = this.master.viewContainerRef;
// Create the component
viewContainerRef1.createComponent(componentFactory);
// Clear the 'select' container so that I can copy over the targeted view only
viewContainerRef2.clear();
// Copy the targeted view into the 'select' container. For now this is hardcoded to copy the first element as an experiment
viewContainerRef2.insert(viewContainerRef1.get(0),0);
this.counter++;
}
loadSampleContentHandler(){
this.loadComponent();
}
}
основной HTML-файл
<div class="l_appletFrame t_appletFrame" [ngClass]="{'l_extendedFrame':!inputControlStructure.summaryViewVisible}">
<div class="l_appletBanner t_appletBanner" >
<div class="l_revisionTypeContainer t_revisionTypeContainer">
<div class="l_revisionLabel">Revision Type:</div>
<div class="l_revisionTypeName">{{inputControlStructure.activeRevisionType}}</div>
</div>
<div class="l_buttonContainer">
<div class="l_button t_button"><div class="l_textBox" (click)="loadSampleContentHandler()">Load</div></div>
<div class="l_button t_button"><div class="l_textBox">Submit</div></div>
<div class="l_button t_button"><div class="l_textBox">Close</div></div>
</div>
</div>
<div class="l_appletContainer" [ngClass]="{'l_extendedContainer':!inputControlStructure.summaryViewVisible}">
<!-- <router-outlet name="primary"></router-outlet>
<router-outlet name="simple"></router-outlet> -->
<!-- <sample-applet></sample-applet> -->
<div class="l_collection"><ng-template applet-collection></ng-template></div>
<div class="l_container"><ng-template applet-container></ng-template></div>
</div>
</div>