I currently have a webpage with a componentcontainer:
HTML:
<ng-container #componentContainer></ng-container>
Typescript:
@ViewChild('componentContainer', { read: ViewContainerRef }) componentContainer: ViewContainerRef;
The component is inserted via the following function:
private createComponent(pageItem: PageItem,
factory: ComponentFactory<BaseTemplate>, isMultiPage: boolean): void {
const compRef = factory.create(this.injector);
if (compRef !== null) {
// Set some variables on the items
compRef.instance.PageComponent = pageItem;
compRef.instance.MultiPageItemPage = isMultiPage;
// Important to watch for changes.
compRef.changeDetectorRef.detectChanges();
this.componentContainer.insert(compRef.hostView);
this.CurrentDynamicComponents.push(
TemplateComponentLoaderService
.createDynamicComponentModelForPageItem(pageItem,
compRef)
);
}
}
I wish to refactor this to work for a list of generic components.
I changed my HTML to:
<div *ngFor="let row of Page.Rows" >
<div *ngFor="let col of row.Columns" class="row">
<div [ngClass]="{ 'col-md-1': col.Width == 1,
'col-md-2': col.Width == 2,
'col-md-3': col.Width == 3,
'col-md-4': col.Width == 4,
'col-md-6': col.Width == 6,
'col-md-12': col.Width == 12 }" test=test>
<ng-container *ngFor="let com of col.Components" #componentContainer>
</ng-container>
</div>
</div>
</div>
This works so far, but obviously I do not have unique Ids for my componentContainer. Im not sure how to go about solving this problem. Does anyone have any advice on how to implement this?
If I understood you correctly you want an index of iterated components. So you can use index
of ngFor
:
<ng-container *ngFor="let com of col.Components; let i = index" #componentContainer>
<!-- here you can use i as an index to your component -->
</ng-container>
UPDATE:
There is no way to style <ng-container/>
because <ng-container/>
is not inserted in HTML, however, we can style your component like this:
<ng-container *ngFor="let com of col.Components; let i = index" #componentContainer>
<com [ngStyle]="{'font-size': fontSize+'px'}"></com>
</ng-container>