最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 5 - Dynamic component loader - Cannot read property 'viewContainerRef' of undefined - Stack

programmeradmin0浏览0评论

I am trying to make the dynamically load ponents in Angular 5. I use the Angular Guide for this, but I am stuck now. The thing is; I get the following error:

ERROR TypeError: Cannot read property 'viewContainerRef' of undefined

The error is in my ChecklistComponent at

const viewContainerRef = this.appHost.viewContainerRef;

For some reason appHost is undefined and I have no idea why.

Here is the rest of my code:

checklistponent.ts

import {
    AfterViewInit, Component, ComponentFactoryResolver, Input, OnInit, ViewChild,
    ViewEncapsulation
} from '@angular/core';
import {ChecklistDirective} from "./checklist.directive";
import {ChecklistMainComponent} from "./checklist-main/checklist-mainponent";

@Component({
    selector: 'app-checklist',
    templateUrl: './checklistponent.html',
    styleUrls: ['./checklistponent.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ChecklistComponent implements OnInit {

    @ViewChild('modalElement') modalElement;
    @ViewChild(ChecklistDirective) appHost: ChecklistDirective;

    constructor(private ponentFactoryResolver: ComponentFactoryResolver) {
    }

    ngOnInit() {
        this.loadComponent();
    }

    loadComponent() {

        const ponentFactory = thisponentFactoryResolver.resolveComponentFactory(ChecklistMainComponent);
        const viewContainerRef = this.appHost.viewContainerRef;
        viewContainerRef.clear();
        const ponentRef = viewContainerRef.createComponent(ponentFactory);

    }

}

checklistponent.html

<ng-template #modalElement let-c="close" let-d="dismiss">
    <div class="modal-header">
        <h4 class="modal-title">{{ 'Checklist'| translate }}</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <ng-template appHost></ng-template>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" (click)="c('Close click')">{{ 'Close'| translate }}</button>
        <button type="button" class="btn btn-primary" (click)="onConfirm($event)">{{ 'Confirm'| translate }}</button>
    </div>
</ng-template>

checklist.directive.ts

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

@Directive({
  selector: '[appHost]'
})
export class ChecklistDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

checklist.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/mon';
import { ChecklistComponent } from './checklistponent';
import {DirectivesModule} from '../../theme/directives/directives.module';
import {TranslateModule} from '@ngx-translate/core';
import {AppCommonPipesModule} from '../../pipes/mon.pipes.module';
import {SharedTaskModule} from '../task/shared.task.module';

@NgModule({
  imports: [
    CommonModule,
    DirectivesModule,
    SharedTaskModule,
    TranslateModule,
    AppCommonPipesModule,
  ],
  declarations: [
    ChecklistComponent
  ]
})
export class ChecklistModule { }

shared.checklist.module.ts

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/mon';
import {PerfectScrollbarModule} from 'ngx-perfect-scrollbar';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {FormModule} from '../../ponents/form/form.module';
import { MultiselectDropdownModule } from 'angular-2-dropdown-multiselect';
import {DirectivesModule} from '../../theme/directives/directives.module';
import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {SharedModalModule} from '../../ponents/model/shared.modal.module';
import {AppCommonPipesModule} from '../../pipes/mon.pipes.module';
import {SharedDirectiveModule} from '../../directives/shared.directive.module';
import { TranslateModule } from '@ngx-translate/core';
import {ChecklistComponent} from "./checklistponent";
import {ChecklistMainComponent} from "./checklist-main/checklist-mainponent";
import {ChecklistViewComponent} from "./checklist-view/checklist-viewponent";
import {ChecklistMutateComponent} from "./checklist-mutate/checklist-mutateponent";
import {ChecklistDirective} from "./checklist.directive";

@NgModule({
    imports: [
        CommonModule,
        PerfectScrollbarModule,
        NgxDatatableModule,
        FormsModule,
        FormModule,
        ReactiveFormsModule,
        MultiselectDropdownModule,
        DirectivesModule,
        OwlDateTimeModule,
        OwlNativeDateTimeModule,
        NgbModule,
        SharedModalModule,
        TranslateModule,
        AppCommonPipesModule,
        SharedDirectiveModule
    ],
    declarations: [
        ChecklistComponent,
        ChecklistMainComponent,
        ChecklistViewComponent,
        ChecklistMutateComponent,
        ChecklistDirective
    ],
    exports: [
        ChecklistComponent,
        ChecklistMainComponent,
        ChecklistViewComponent,
        ChecklistMutateComponent,
        ChecklistDirective
    ],
    entryComponents: [ChecklistMainComponent]
})

export class SharedChecklistModule {
}

checklist-mainponent.ts

import {Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewEncapsulation} from '@angular/core';
import {
    CollectionHttpRequestOptions, CollectionHttpResponse,
    OrderByRequestOptions
} from '../../../services/http.service';
import {ChecklistModel} from '../../../models/checklist.models';
import {ChecklistService} from '../../../services/checklist.service';

@Component({
    selector: 'app-checklist-main',
    templateUrl: './checklist-mainponent.html',
    styleUrls: ['./checklist-mainponent.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ChecklistMainComponent implements OnInit {

    isLoading = false;
    tableInfo: any = {offset: 0, limit: 10};
    collectionRequestModel = new CollectionHttpRequestOptions();
    collectionResponseModel = new CollectionHttpResponse<ChecklistModel>();

    @ViewChild('myTable') table: any;
    @Input() formData: ChecklistModel = new ChecklistModel();
    @Output() activate = new EventEmitter();

    constructor(private checklistService: ChecklistService) {}

    ngOnInit() {
        this.setPage(this.tableInfo);
    }

    public onSearch(event) {
        this.collectionRequestModel.page = 1;
        this.collectionRequestModel.search = event.target.value;
        this.load();
    }

    load() {
        this.isLoading = true;
        this.checklistService.getCollection(this.collectionRequestModel).subscribe(response => {
            this.collectionResponseModel = response;
            this.isLoading = false;
        });
    }

    onActivate(event) {
        this.activate.emit(event);

        if (event.type === "click") {
            this.loadChecklist(event);
        }
    }

    setPage(pageInfo: any) {
        this.collectionRequestModel.page = (pageInfo.offset + 1);
        this.collectionRequestModel.itemsPerPage = pageInfo.limit;
        this.load();
    }

    onSort(event: any) {
        const sort = event.sorts[0];
        const orderBy = new OrderByRequestOptions();
        orderBy.key = sort.prop;
        orderBy.direction = sort.dir.toUpperCase();

        this.collectionRequestModel.orderBy = [orderBy];

        this.load();
    }

    loadChecklist(event) {
        console.log("Yay");
    }

}

checklist-mainponent.html

<div class="header">
    <button class="btn btn-outline-success new-checklist-btn">{{ 'New Checklist'| translate }}</button>
</div>

<div class="body">
    <h5>Current Checklists</h5>

    <ngx-datatable #myTable class="material" [rows]="collectionResponseModel.items" [columnMode]="'force'"
                   [headerHeight]="50"
                   [footerHeight]="50" [rowHeight]="'fixed'" [externalPaging]="true"
                   [count]="collectionResponseModel.totalCount" [offset]="tableInfo.offset"
                   [limit]="tableInfo.limit" [loadingIndicator]="isLoading" (activate)="onActivate($event)"
                   (page)='setPage($event)' (sort)='onSort($event)'>

        <ngx-datatable-column name="Naam" prop="name" [flexGrow]="1">
            <ng-template let-row="row" let-value="value" ngx-datatable-cell-template>
                {{value}}
            </ng-template>
        </ngx-datatable-column>

    </ngx-datatable>

</div>

I am trying to make the dynamically load ponents in Angular 5. I use the Angular Guide for this, but I am stuck now. The thing is; I get the following error:

ERROR TypeError: Cannot read property 'viewContainerRef' of undefined

The error is in my ChecklistComponent at

const viewContainerRef = this.appHost.viewContainerRef;

For some reason appHost is undefined and I have no idea why.

Here is the rest of my code:

checklist.ponent.ts

import {
    AfterViewInit, Component, ComponentFactoryResolver, Input, OnInit, ViewChild,
    ViewEncapsulation
} from '@angular/core';
import {ChecklistDirective} from "./checklist.directive";
import {ChecklistMainComponent} from "./checklist-main/checklist-main.ponent";

@Component({
    selector: 'app-checklist',
    templateUrl: './checklist.ponent.html',
    styleUrls: ['./checklist.ponent.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ChecklistComponent implements OnInit {

    @ViewChild('modalElement') modalElement;
    @ViewChild(ChecklistDirective) appHost: ChecklistDirective;

    constructor(private ponentFactoryResolver: ComponentFactoryResolver) {
    }

    ngOnInit() {
        this.loadComponent();
    }

    loadComponent() {

        const ponentFactory = this.ponentFactoryResolver.resolveComponentFactory(ChecklistMainComponent);
        const viewContainerRef = this.appHost.viewContainerRef;
        viewContainerRef.clear();
        const ponentRef = viewContainerRef.createComponent(ponentFactory);

    }

}

checklist.ponent.html

<ng-template #modalElement let-c="close" let-d="dismiss">
    <div class="modal-header">
        <h4 class="modal-title">{{ 'Checklist'| translate }}</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <ng-template appHost></ng-template>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" (click)="c('Close click')">{{ 'Close'| translate }}</button>
        <button type="button" class="btn btn-primary" (click)="onConfirm($event)">{{ 'Confirm'| translate }}</button>
    </div>
</ng-template>

checklist.directive.ts

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

@Directive({
  selector: '[appHost]'
})
export class ChecklistDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

checklist.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/mon';
import { ChecklistComponent } from './checklist.ponent';
import {DirectivesModule} from '../../theme/directives/directives.module';
import {TranslateModule} from '@ngx-translate/core';
import {AppCommonPipesModule} from '../../pipes/mon.pipes.module';
import {SharedTaskModule} from '../task/shared.task.module';

@NgModule({
  imports: [
    CommonModule,
    DirectivesModule,
    SharedTaskModule,
    TranslateModule,
    AppCommonPipesModule,
  ],
  declarations: [
    ChecklistComponent
  ]
})
export class ChecklistModule { }

shared.checklist.module.ts

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/mon';
import {PerfectScrollbarModule} from 'ngx-perfect-scrollbar';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {FormModule} from '../../ponents/form/form.module';
import { MultiselectDropdownModule } from 'angular-2-dropdown-multiselect';
import {DirectivesModule} from '../../theme/directives/directives.module';
import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {SharedModalModule} from '../../ponents/model/shared.modal.module';
import {AppCommonPipesModule} from '../../pipes/mon.pipes.module';
import {SharedDirectiveModule} from '../../directives/shared.directive.module';
import { TranslateModule } from '@ngx-translate/core';
import {ChecklistComponent} from "./checklist.ponent";
import {ChecklistMainComponent} from "./checklist-main/checklist-main.ponent";
import {ChecklistViewComponent} from "./checklist-view/checklist-view.ponent";
import {ChecklistMutateComponent} from "./checklist-mutate/checklist-mutate.ponent";
import {ChecklistDirective} from "./checklist.directive";

@NgModule({
    imports: [
        CommonModule,
        PerfectScrollbarModule,
        NgxDatatableModule,
        FormsModule,
        FormModule,
        ReactiveFormsModule,
        MultiselectDropdownModule,
        DirectivesModule,
        OwlDateTimeModule,
        OwlNativeDateTimeModule,
        NgbModule,
        SharedModalModule,
        TranslateModule,
        AppCommonPipesModule,
        SharedDirectiveModule
    ],
    declarations: [
        ChecklistComponent,
        ChecklistMainComponent,
        ChecklistViewComponent,
        ChecklistMutateComponent,
        ChecklistDirective
    ],
    exports: [
        ChecklistComponent,
        ChecklistMainComponent,
        ChecklistViewComponent,
        ChecklistMutateComponent,
        ChecklistDirective
    ],
    entryComponents: [ChecklistMainComponent]
})

export class SharedChecklistModule {
}

checklist-main.ponent.ts

import {Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewEncapsulation} from '@angular/core';
import {
    CollectionHttpRequestOptions, CollectionHttpResponse,
    OrderByRequestOptions
} from '../../../services/http.service';
import {ChecklistModel} from '../../../models/checklist.models';
import {ChecklistService} from '../../../services/checklist.service';

@Component({
    selector: 'app-checklist-main',
    templateUrl: './checklist-main.ponent.html',
    styleUrls: ['./checklist-main.ponent.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ChecklistMainComponent implements OnInit {

    isLoading = false;
    tableInfo: any = {offset: 0, limit: 10};
    collectionRequestModel = new CollectionHttpRequestOptions();
    collectionResponseModel = new CollectionHttpResponse<ChecklistModel>();

    @ViewChild('myTable') table: any;
    @Input() formData: ChecklistModel = new ChecklistModel();
    @Output() activate = new EventEmitter();

    constructor(private checklistService: ChecklistService) {}

    ngOnInit() {
        this.setPage(this.tableInfo);
    }

    public onSearch(event) {
        this.collectionRequestModel.page = 1;
        this.collectionRequestModel.search = event.target.value;
        this.load();
    }

    load() {
        this.isLoading = true;
        this.checklistService.getCollection(this.collectionRequestModel).subscribe(response => {
            this.collectionResponseModel = response;
            this.isLoading = false;
        });
    }

    onActivate(event) {
        this.activate.emit(event);

        if (event.type === "click") {
            this.loadChecklist(event);
        }
    }

    setPage(pageInfo: any) {
        this.collectionRequestModel.page = (pageInfo.offset + 1);
        this.collectionRequestModel.itemsPerPage = pageInfo.limit;
        this.load();
    }

    onSort(event: any) {
        const sort = event.sorts[0];
        const orderBy = new OrderByRequestOptions();
        orderBy.key = sort.prop;
        orderBy.direction = sort.dir.toUpperCase();

        this.collectionRequestModel.orderBy = [orderBy];

        this.load();
    }

    loadChecklist(event) {
        console.log("Yay");
    }

}

checklist-main.ponent.html

<div class="header">
    <button class="btn btn-outline-success new-checklist-btn">{{ 'New Checklist'| translate }}</button>
</div>

<div class="body">
    <h5>Current Checklists</h5>

    <ngx-datatable #myTable class="material" [rows]="collectionResponseModel.items" [columnMode]="'force'"
                   [headerHeight]="50"
                   [footerHeight]="50" [rowHeight]="'fixed'" [externalPaging]="true"
                   [count]="collectionResponseModel.totalCount" [offset]="tableInfo.offset"
                   [limit]="tableInfo.limit" [loadingIndicator]="isLoading" (activate)="onActivate($event)"
                   (page)='setPage($event)' (sort)='onSort($event)'>

        <ngx-datatable-column name="Naam" prop="name" [flexGrow]="1">
            <ng-template let-row="row" let-value="value" ngx-datatable-cell-template>
                {{value}}
            </ng-template>
        </ngx-datatable-column>

    </ngx-datatable>

</div>
Share Improve this question edited Apr 11, 2018 at 13:03 Luuk Wuijster asked Apr 11, 2018 at 8:07 Luuk WuijsterLuuk Wuijster 6,8788 gold badges35 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

you are using ng-template (<ng-template #modalElement let-c="close" let-d="dismiss">) which will not be rendered until you tell angular to do so. this means the second/nested ng-template which uses the directive is never rendered because the outer ng-template is not rendered.

Have a look at https://stackblitz./edit/angular-tjr4uq if you remove the code in ngOnInit you'll see that a) nothing within the outer ng-template is rendered and b) element will be undefined in ngAfterViewInit

EDIT (maybe try that):

import {
  AfterViewInit, ViewContainerRef, Component, ComponentFactoryResolver, Input, OnInit, ViewChild,
    ViewEncapsulation
} from '@angular/core';
import { ChecklistDirective } from "./checklist.directive";
import { ChecklistMainComponent } from "./checklist-main/checklist-main.ponent";

@Component({
  selector: 'app-checklist',
  templateUrl: './checklist.ponent.html',
  styleUrls: ['./checklist.ponent.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ChecklistComponent implements OnInit {

  @ViewChild('modalElement') modalElement;
  @ViewChild(ChecklistDirective) appHost: ChecklistDirective;

  constructor(private vc: ViewContainerRef, private ponentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    this.vc.createEmbeddedView(this.modalElement);
  }

  ngAfterViewInit() {
    this.loadComponent();
  }

  loadComponent() {

    const ponentFactory = this.ponentFactoryResolver.resolveComponentFactory(ChecklistMainComponent);
    const viewContainerRef = this.appHost.viewContainerRef;
    viewContainerRef.clear();
    const ponentRef = viewContainerRef.createComponent(ponentFactory);

  }

}

@ViewChild() decorated properties will only be available after ngAfterViewInit lifecycle hook and you're calling your load ponent function on ngOnInit, which happens to execute before your @ViewChild() is available.

发布评论

评论列表(0)

  1. 暂无评论