Mikou
Mikou

Reputation: 651

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

Upvotes: 0

Views: 769

Answers (2)

Kunso Solutions
Kunso Solutions

Reputation: 7630

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

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691913

private word: "hello";

This defines a field named "word", whose type is "hello". I.e. 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.

Upvotes: 2

Related Questions