Angular @ViewChild未初始化
我在Angular 2中通过在tab中动态加载组件来创建tab向导组件。我借用了从线程动态加载组件的思想。我还使用了角材质2来实现选项卡功能 我的动态加载程序组件定义如下Angular @ViewChild未初始化,angular,angular-material,Angular,Angular Material,我在Angular 2中通过在tab中动态加载组件来创建tab向导组件。我借用了从线程动态加载组件的思想。我还使用了角材质2来实现选项卡功能 我的动态加载程序组件定义如下 import {Component, ViewChild,ViewContainerRef,Input, ComponentRef,ComponentResolver,ComponentFactory, OnInit,OnChanges,AfterViewInit,OnDestroy} from '@angul
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();
}
}
}
import{Component,ViewChild,ViewContainerRef,Input,
ComponentRef、ComponentResolver、ComponentFactory、,
来自“@angular/core”的OnInit、OnChanges、AfterViewInit、OnDestroy}
从“@angular2物料/组件/制表组/制表组”导入{MD_制表组};
从'@angular2 material/components/toolbar/toolbar'导入{MdToolbar};
从“@angular2 material/components/input/input”导入{MdInput};
从“./test.component”导入{test}
@组成部分({
选择器:“向导”,
样式URL:['./app/wizard.component.css'],
模板:`
表1
`,
指令:[MD\u选项卡\u组\u指令,MdToolbar,MdInput],
})
导出类向导{
@ViewChild('target',{read:ViewContainerRef})目标:任意;
@Input()类型:任意|字符串;
cmpRef:ComponentRef)位于
匿名函数
()在
ZoneDelegate.prototype.invokeTask
()在
位于ZoneDelegate.prototype.invokeTask的onInvokeTask(评估代码:36:25)
()在
Zone.prototype.runTask
()在
drainMicroTaskQueue
()在
援引
()”
我知道这是因为“target”变量为null,并且没有初始化。
如果我像下面这样在上面的组件中更改模板,将div标记与#target置于material design选项卡组件模板标记之外,那么它工作得非常好。如何使其工作,同时将target div标记保持在material选项卡模板内
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>
`,
模板:`
表1
`,