изменение реализации ViewChild для поддержки нескольких общих компонентов - PullRequest
2 голосов
/ 08 октября 2019

В настоящее время у меня есть веб-страница с компонентом-контейнером:

HTML:

  <ng-container #componentContainer></ng-container>

Машинопись:

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

Компонент вставляется с помощью следующей функции:

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

Я хочу изменить этот код для работы со списком общих компонентов.

Я изменил свой HTML-код на:

<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>

Пока это работает, но, очевидно,У меня нет уникальных идентификаторов для моего componentContainer. Я не уверен, как решить эту проблему. У кого-нибудь есть советы, как это реализовать?

1 Ответ

0 голосов
/ 08 октября 2019

Если я вас правильно понял, вам нужен индекс повторяющихся компонентов. Таким образом, вы можете использовать index из 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>

ОБНОВЛЕНИЕ:

Нет способа стилизовать <ng-container/>, потому что <ng-container/> не вставляется в HTML, однако,мы можем стилизовать ваш компонент так:

<ng-container *ngFor="let com of col.Components; let i = index" #componentContainer>
    <com [ngStyle]="{'font-size': fontSize+'px'}"></com>
</ng-container>
...