0

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

Community
  • 1
  • 1
Mikou
  • 579
  • 1
  • 8
  • 17
  • There is no reason that `this.word` etc. would not be visible within `ngOnInit()`. Their `private` nature is merely a compile-time concept that has no effect on the way the code works. There must be something else going on that we're not seeing. by the way, where is `Comment` defined? As your code stands, this is unlikely to compile, and if you run it anyway, you'll get a `ReferenceError` when `components` is initialized. –  Aug 26 '16 at 18:16
  • Where is Comment defined? Thanks for the question, this is actually a mistake. It should be CommentComponent and CommentComponent is a Component. And it solved my problem. However, I still don't see the variable this.word within the class – Mikou Aug 26 '16 at 18:42
  • I updated the code – Mikou Aug 26 '16 at 18:44

2 Answers2

2
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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

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

Kanso Code
  • 7,479
  • 5
  • 34
  • 49