Невозможно отобразить компонент, используя ViewContainerRef - PullRequest
0 голосов
/ 17 июня 2019

Мне нужно «создать» новый компонент по нажатию кнопки, по умолчанию я хочу показать последний добавленный продукт на странице после загрузки и после навигации по другим продуктам.

Когда я получу весь продукт, в функции complete я вызову метод createComponent() и предоставлю последний идентификатор.

// global variables
@ViewChild('productDetails', {read: ViewContainerRef}) entry: ViewContainerRef;
componentRef: any;

// create child component method
createComponent(id: number) {
  if (this.entry) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(ProductDetailsComponent);
    this.componentRef = this.entry.createComponent(factory);
    this.componentRef.instance.id = this.id = id;
  }
}

// Get list and generate component
ngOnInit() {
  this.list$ = this.listService.getList().subscribe(
    (response: IProducts[]) => {
      response.map((item, index) => {
        if (!this.id) {
          this.id = +item.Id;
        }

        if (!item.IsExpired) {
          item.style = 'card-disabled';
        } else {
          item.style = this.colors[index];
        }

        this.list.push(item);
      });
    },
    reason => console.error(reason),
    () => this.createComponent(this.id)
  );
}

Но в первый раз консоль сказала мне TypeError: Cannot read property 'clear' of undefined.Но после других нажатий на другой продукт компонент отображается правильно.

Ответы [ 3 ]

0 голосов
/ 17 июня 2019

Исходя из вашего ответа на мой комментарий: попробуйте переместить этот код из ngOnInit в ngAfterViewInit, я думаю, тогда ViewContainerRef должен быть готов

0 голосов
/ 17 июня 2019

viewChild доступно на AfterViewInit, например

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements  AfterViewInit {
  .....

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

  ngAfterViewInit() {
    console.log('Values on ngAfterViewInit():');
    console.log("entry:", this.entry);
  }  

  .....
}

временное изображение будет удалено

temporary will be removed

0 голосов
/ 17 июня 2019

есть ли у вас экземпляр productDetails в вашем основном компоненте?

вам нужно добавить productDetails в ваш шаблон / html в html шаблон добавить элемент div:

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