Angular 5-动态组件加载程序-无法读取未定义的属性'viewContainerRef' [英] Angular 5 - Dynamic component loader - Cannot read property 'viewContainerRef' of undefined

查看:87
本文介绍了Angular 5-动态组件加载程序-无法读取未定义的属性'viewContainerRef'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Angular 5中动态加载组件.我使用 Angular Guide ,但是现在我被困住了.事情是;我收到以下错误:

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

错误TypeError:无法读取未定义的属性'viewContainerRef'

ERROR TypeError: Cannot read property 'viewContainerRef' of undefined

错误出现在我的ChecklistComponent

const viewContainerRef = this.appHost.viewContainerRef;

由于某些原因,appHost未定义,我也不知道为什么.

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

这是我其余的代码:

checklist.component.ts

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

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

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

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    ngOnInit() {
        this.loadComponent();
    }

    loadComponent() {

        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChecklistMainComponent);
        const viewContainerRef = this.appHost.viewContainerRef;
        viewContainerRef.clear();
        const componentRef = viewContainerRef.createComponent(componentFactory);

    }

}

checklist.component.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/common';
import { ChecklistComponent } from './checklist.component';
import {DirectivesModule} from '../../theme/directives/directives.module';
import {TranslateModule} from '@ngx-translate/core';
import {AppCommonPipesModule} from '../../pipes/common.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/common';
import {PerfectScrollbarModule} from 'ngx-perfect-scrollbar';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {FormModule} from '../../components/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 '../../components/model/shared.modal.module';
import {AppCommonPipesModule} from '../../pipes/common.pipes.module';
import {SharedDirectiveModule} from '../../directives/shared.directive.module';
import { TranslateModule } from '@ngx-translate/core';
import {ChecklistComponent} from "./checklist.component";
import {ChecklistMainComponent} from "./checklist-main/checklist-main.component";
import {ChecklistViewComponent} from "./checklist-view/checklist-view.component";
import {ChecklistMutateComponent} from "./checklist-mutate/checklist-mutate.component";
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.component.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.component.html',
    styleUrls: ['./checklist-main.component.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.component.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>

推荐答案

您正在使用ng-template(<ng-template #modalElement let-c="close" let-d="dismiss">),除非您告诉angular这样做,否则它不会被渲染. 这意味着使用该指令的第二个/嵌套ng-template不会被渲染,因为外部的ng-template不会被渲染.

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.

看看 https://stackblitz.com/edit/angular-tjr4uq 如果删除ngOnInit中的代码,您将看到a)外部ng-template中没有呈现任何内容,并且b)elementngAfterViewInit

Have a look at https://stackblitz.com/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.component";

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

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

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

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

  ngAfterViewInit() {
    this.loadComponent();
  }

  loadComponent() {

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChecklistMainComponent);
    const viewContainerRef = this.appHost.viewContainerRef;
    viewContainerRef.clear();
    const componentRef = viewContainerRef.createComponent(componentFactory);

  }

}

这篇关于Angular 5-动态组件加载程序-无法读取未定义的属性'viewContainerRef'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆