Загрузчик компонентов Dynami c - невозможно прочитать свойство viewContainerRef из undefined - PullRequest
0 голосов
/ 29 мая 2020

Я выполняю все шаги руководства по рекламным баннерам на Angular .io. Но в конце, после всех настроек, я получаю сообщение об ошибке из этого компонента и функции:

Ad-banner.component TS

loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    const adItem = this.ads[this.currentAdIndex];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    const viewContainerRef = this.adHost.viewContainerRef; ---->ERROR comes from this Line
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

Я получаю журнал правильно, приходят данные героя в домашний компонент, где я буду показывать рекламу, но не с ошибкой, так может ли кто-нибудь со мной разобраться?

EDIT Основная директива

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]'
})
export class AdDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

1 Ответ

1 голос
/ 29 мая 2020

Ваш компонент HTML должен быть: -

<div class="ad-banner-example">
              <h3>Advertisements</h3>
              <ng-template ad-host></ng-template>
            </div>

Ваш компонент Ts должен иметь: -

@ViewChild(AdDirective, {static: true}) adHost: AdDirective;

AdhostDirective должен быть в объявлениях вашего модуля.

, и вы должны вызывать this.loadComponent (); в ngoninit.

...