简体   繁体   English

私有成员的ngOnInit可见性

[英]ngOnInit visibility of private member

I have the following Directive. 我有以下指令。

From within ngOnInit, both this.word and this.components are "undefined". 在ngOnInit中,this.word和this.components均为“未定义”。

Could anyone explain me why? 谁能解释我为什么?

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);

  }
}

Heavily inspired by this: Outputting array of components in Angular 2 受此启发: 在Angular 2中输出组件数组

private word: "hello";

This defines a field named "word", whose type is "hello". 这定义了一个名为“ word”的字段,其类型为“ hello”。 Ie the only valid value (except for undefined and null) it can have is "hello". 即,它可以具有的唯一有效值(“ hello”除外)。 It doesn't initialize the field, so it's still undefined. 它不会初始化该字段,因此仍未定义。 If you want a field of type string, initialized to "hello", you need 如果要使用字符串类型的字段(初始化为“ hello”),则需要

private word = "hello";

which is a shorter form (thanks to type inference) for 这是较短的形式(由于类型推断)

private word: string = "hello";

The same explanation stands for components . 相同的解释代表components

The reason is pretty simple, you just confused the assignment of type and value . 原因很简单,您只是混淆了typevalue的分配。

Now you have: private word: "hello"; 现在您有了: private word: "hello";

Should be: private word: string = "hello"; 应该是: private word: string = "hello";

After : goes type, then default value after = . After :输入,然后=之后的默认值。

access_modificatior variable_name: type = default_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM