我有以下指令。
在ngOnInit中,this.word和this.components都是“未定义”。
有人能解释我为什么吗?
import { Directive , Input, Output, ViewContainerRef, ComponentRef, DynamicComponentLoader, EventEmitter, OnInit, NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Widget } from '../widget.model';
import { CommentComponent } from './comment.component';
@Directive({selector: 'widget-factory'})
export class WidgetFactory {
@Input() name: any;
@Input() id: Number;
@Output() loaded = new EventEmitter();
private components: { 'Comment': CommentComponent };
private word: "hello";
constructor(
private _dcl: DynamicComponentLoader,
private _elementRef: ViewContainerRef
) {
}
ngOnInit() {
// Get the current element
console.log(this.word);
let component: any;
//if(this[name] === 'Comment') {
component = CommentComponent
//}
this._dcl.loadNextToLocation(CommentComponent, this._elementRef);
console.log(this.name);
}
}
答案 0 :(得分:2)
private word: "hello";
这定义了一个名为“word”的字段,其类型是“hello”。即它可以拥有的唯一有效值(undefined和null除外)是“hello”。它没有初始化字段,因此它仍未定义。如果你想要一个字符串类型的字段,初始化为“hello”,你需要
private word = "hello";
是
的较短形式(由于类型推断)private word: string = "hello";
相同的解释代表components
。
答案 1 :(得分:1)
原因很简单,你只是混淆了Get http://x.com/Themes/y/fonts/fontawesome-webfont.woff2?v=4.3.0
GET http://x.com/Themes/y/fonts/fontawesome-webfont.woff?v=4.3.0
GET http://x.com/Themes/y/fonts/fontawesome-webfont.ttf?v=4.3.0 404 (Not Found)
和type
的分配。
现在你有:value
应该是:private word: "hello";
private word: string = "hello";
输入后,:
后的默认值。
=