我通过动态加载选项卡中的组件在Angular 2中创建选项卡向导组件 . 我借用了从this SO线程动态加载组件的想法 . 我也使用 Angular Material 2 作为标签功能 .
我的动态加载程序组件定义如下 .
import {Component, ViewChild,ViewContainerRef,Input,
ComponentRef,ComponentResolver,ComponentFactory,
OnInit,OnChanges,AfterViewInit,OnDestroy} from '@angular/core'
import {MD_TAB_GROUP_DIRECTIVES} from '@angular2-material/components/tab-group/tab-group';
import {MdToolbar} from '@angular2-material/components/toolbar/toolbar';
import {MdInput} from '@angular2-material/components/input/input';
import {test} from './test.component'
@Component({
selector: 'wizard',
styleUrls : ['./app/wizard.component.css'],
template: `
<md-tab-group class="demo-tab-group">
<md-tab>
<template md-tab-label>Tab 1</template>
<template md-tab-content>
<div #target></div>
</template>
</md-tab>
</md-tab-group>
`,
directives: [MD_TAB_GROUP_DIRECTIVES, MdToolbar, MdInput],
})
export class wizard {
@ViewChild('target', {read: ViewContainerRef}) target:any;
@Input() type: any|string;
cmpRef:ComponentRef<any>;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {
this.type = test;
console.log("This is loader.");
}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then ((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
我运行它时遇到以下错误 .
“错误:未捕获(在承诺中):TypeError:无法在resolvePromise中获取未定义或空引用的属性”createComponent“(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:538:26 )在ZoneDelegate.prototype.invokeTask的匿名函数(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:574:18)中(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:354:18)在ZoneDelegate.prototype.invokeTask的onInvokeTask(eval代码:36:25)(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:354:18) )在drainMicroTaskQueue的Zone.prototype.runTask(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:256:22)处(http:// localhost:3000 / node_modules / zone.js / dist) /zone.js:474:26)在调用时(http:// localhost:3000 / node_modules / zone.js / dist / zone.js:426:22)“
我知道它因为“target”变量为null而没有初始化 . 如果我通过在材料设计标签组件模板标签之外的#target使用div标签来更改上面组件中的模板,那么它的工作完全正常 . 如何在保持目标div标签仍然在材料选项卡模板中的同时使其工作?
template: `
<div #target></div>
<md-tab-group class="demo-tab-group">
<md-tab>
<template md-tab-label>Tab 1</template>
<template md-tab-content></template>
</md-tab>
</md-tab-group>
`,