簡體   English   中英

私有成員的ngOnInit可見性

[英]ngOnInit visibility of private member

我有以下指令。

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

  }
}

受此啟發: 在Angular 2中輸出組件數組

private word: "hello";

這定義了一個名為“ word”的字段,其類型為“ hello”。 即,它可以具有的唯一有效值(“ hello”除外)。 它不會初始化該字段,因此仍未定義。 如果要使用字符串類型的字段(初始化為“ hello”),則需要

private word = "hello";

這是較短的形式(由於類型推斷)

private word: string = "hello";

相同的解釋代表components

原因很簡單,您只是混淆了typevalue的分配。

現在您有了: private word: "hello";

應該是: private word: string = "hello";

After :輸入,然后=之后的默認值。

access_modificatior variable_name: type = default_value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM