【发布时间】:2018-07-27 09:37:52
【问题描述】:
我正在关注this 关于如何在运行时动态加载组件的教程,但遇到了我的@ViewChild 是undefined 的问题。
这是我的指令`。
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[dynamic-event]'
})
export class EventDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
组件注入模板的位置(feed.component.html):
<ng-template dynamic-event></ng-template>
feed.component.ts
import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { Event } from '../../models/event';
import { FeedService } from '../../services/feed.service';
import { EventDirective } from '../../directives/event.directive';
import { EventComponent } from '../event.component/event.component';
@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {
//feeds
feeds: Event[];
//Get directive which contains ViewContainerRef
@ViewChild(EventDirective) eventHost: EventDirective;
constructor(private feedService: FeedService,
private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
//this.getFeeds();
}
ngAfterViewChecked() {
this.getFeeds();
}
getFeeds(): void {
this.feedService
.getFeeds()
.subscribe(o =>
{
this.feeds = o;
this.populateFeeds();
});
}
populateFeeds(): void {
//resolve my component dynamically
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(EventComponent);
//get FeedComponent's ViewContainer (serves as parent viewContainer)
let viewContainerRef = this.eventHost.viewContainerRef;
viewContainerRef.clear();
if (this.feeds !== undefined || this.feeds !== null || this.feeds.entries.length !== 0){
this.feeds.forEach(x => {
let component = viewContainerRef.createComponent(componentFactory);
(<EventComponent>component.instance).event = x;
});
}
}
}
我的@ViewChild 未定义,我不知道为什么。有什么帮助吗?
【问题讨论】:
标签: angular angular-directive viewchild