【发布时间】:2023-03-07 02:50:01
【问题描述】:
我有以下指令。
在 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);
}
}
【问题讨论】:
-
没有理由
this.word等在ngOnInit()中不可见。他们的private性质只是一个编译时概念,对代码的工作方式没有影响。一定有其他我们没有看到的事情发生。顺便问一下,Comment是在哪里定义的?就你的代码而言,这不太可能编译,如果你仍然运行它,当components初始化时,你会得到一个ReferenceError。 -
评论在哪里定义?感谢您的提问,这实际上是一个错误。它应该是 CommentComponent 并且 CommentComponent 是一个组件。它解决了我的问题。但是,我仍然没有在类中看到变量 this.word
-
我更新了代码
标签: angular angular2-directives ngoninit