Angular Ngonit私有成员的可见性
我有以下指示 在ngOnInit中,this.word和this.components都是“未定义的” 谁能解释一下原因吗Angular Ngonit私有成员的可见性,angular,angular2-directives,ngoninit,Angular,Angular2 Directives,Ngoninit,我有以下指示 在ngOnInit中,this.word和this.components都是“未定义的” 谁能解释一下原因吗 import { Directive , Input, Output, ViewContainerRef, ComponentRef, DynamicComponentLoader, EventEmitter, OnInit, NgModule} from '@angular/core'; import { BrowserModule } from '@angular/pl
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);
}
}
深受此启发:
这定义了一个名为“word”的字段,其类型为“hello”。也就是说,它可以拥有的唯一有效值(未定义和空值除外)是“hello”。它没有初始化字段,因此它仍然是未定义的。如果您想要一个字符串类型的字段,初始化为“hello”,您需要
private word = "hello";
这是一种较短的形式(由于类型推断)
相同的解释表示组件
这定义了一个名为“word”的字段,其类型为“hello”。也就是说,它可以拥有的唯一有效值(未定义和空值除外)是“hello”。它没有初始化字段,因此它仍然是未定义的。如果您想要一个字符串类型的字段,初始化为“hello”,您需要
private word = "hello";
这是一个较短的形式(由于类型推断)
相同的解释表示
组件
原因很简单,您只是混淆了类型
和值
的分配
现在你有了:private单词:“hello”代码>
应该是:private-word:string=“hello”代码>
在之后:
输入,然后在=
之后输入默认值
access\u modificationor variable\u name:type=default\u value
原因很简单,您只是混淆了type
和value
的赋值
现在你有了:private单词:“hello”代码>
应该是:private-word:string=“hello”代码>
在之后:
输入,然后在=
之后输入默认值
access\u modificationor variable\u name:type=default\u value
没有理由在ngOnInit()中看不到这个词。它们的private
本质只是一个编译时概念,对代码的工作方式没有影响。一定还有别的事情我们没看到。顺便问一下,Comment
在哪里定义?就您的代码而言,这不太可能编译,如果您仍然运行它,当初始化组件时,您将得到ReferenceError
。注释定义在哪里?谢谢你的提问,这实际上是个错误。它应该是CommentComponent,CommentComponent是一个组件。它解决了我的问题。但是,我仍然没有看到classI中的变量this.word更新了代码没有理由this.word等在ngOnInit()中不可见。它们的private
本质只是一个编译时概念,对代码的工作方式没有影响。一定还有别的事情我们没看到。顺便问一下,Comment
在哪里定义?就您的代码而言,这不太可能编译,如果您仍然运行它,当初始化组件时,您将得到ReferenceError
。注释定义在哪里?谢谢你的提问,这实际上是个错误。它应该是CommentComponent,CommentComponent是一个组件。它解决了我的问题。但是,我仍然没有看到classI中的变量this.word更新了代码
private word: string = "hello";