Как вызвать @ViewChild для шаблона, объявленного внутри * ngIf? - PullRequest
0 голосов
/ 12 октября 2019

Я вызываю компонент динамически внутри таблицы. Я использую ViewContainerRef для динамического рендеринга компонента внутри шаблона. Но шаблон, который находится внутри другого элемента, не заполняется. Возможно, потому что при объявлении @ViewChild другой ng-шаблон отсутствует в DOM.

Вот код компонента:

@ViewChild('loadComponent', {static: false, read: ViewContainerRef}) ref;


ngAfterViewChecked(): void {

    const componentFactory = 
    this._componentFactoryResolver.resolveComponentFactory(DynamicComponent);
    const ref = this.ref.createComponent(componentFactory);
    ref.changeDetectorRef.detectChanges();
  }

Вот код шаблона:

<table>
...
    <tr *ngFor="let data of dataItems">       

       <td *ngIf="data.isDisplay">        

       <ng-template #loadComponent></ng-template> // this does'nt work  

    </td>

...

Итак, как мне убедиться, что компонент отображается внутри td после динамической оценки кода td?

1 Ответ

1 голос
/ 13 октября 2019

Редактировать :

Получив все templateRefs нестатически, вы можете перебирать ссылки на шаблоны и создавать по одному компоненту для каждого, после чего вам нужно только прикрепить его к некоторымЭлемент DOM (родительский шаблон templateRef)

@ViewChildren("dynamicTemplateId") private refs: QueryList<"dynamic">;

this.refs.forEach((r: any) => {
  // Create a new instance of the component
  const dynamicComponentRef = componentFactory.create(this.injector);

  // If you don't attach to appRef ng hook cycles won't work inside the component 
  // You can skip adding to application ref but you'll be needing to call .detectChanges() for every changes 
  this.appRef.attachView(dynamicComponentRef.hostView);

  // Append to parentElement since templateRef isn't a element itself
  r.elementRef.nativeElement.parentElement.appendChild(dynamicComponentRef.location.nativeElement);
});

Вот рабочий пример: https://stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts

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