简体   繁体   中英

ngOnInit visibility of private member

I have the following Directive.

From within ngOnInit, both this.word and this.components are "undefined".

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

private word: "hello";

This defines a field named "word", whose type is "hello". Ie the only valid value (except for undefined and null) it can have is "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

private word = "hello";

which is a shorter form (thanks to type inference) for

private word: string = "hello";

The same explanation stands for components .

The reason is pretty simple, you just confused the assignment of type and value .

Now you have: private word: "hello";

Should be: private word: string = "hello";

After : goes type, then default value after = .

access_modificatior variable_name: type = default_value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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