Search code examples
angularangular-directive

Angular 2 problems with directive input / output


I cannot bind variables input / outputs. I don't know what I am doing wrong.

HTML

<p [timeDelta]="'2016-09-20 00:00:00'">{{delta}}</p>

Here is my directive:

import { Directive, ElementRef, Input, Output, Renderer, EventEmitter } from '@angular/core';

@Directive({ selector: '[timeDelta]' })
export class TimeDeltaDirective {
    @Input('timeDelta') myDate: string;
    @Output() delta: string;

    constructor(renderer: Renderer, el: ElementRef) {
        console.log(this);
        console.log(this.myDate);
        this.delta = (this.myDate);
    }
}

The first console.log(this) returns correct value:

  • TimeDeltaDirective object {delta: undefined, myDate: "2016-09-20 00:00:00"}

The second one returns: undefined

But why? A microsecond before it outputs the whole object with myDate in it, but while accessing this.myDate it returns undefined.

Please help me. Thank you


Solution

  • @Inputs() are not yet assigned when the constructor() is executed.

    Use ngOnInit hook instead of constructor

      constructor(renderer: Renderer, el: ElementRef) {
        console.log(this);
        console.log(this.myDate);
        this.delta = (this.myDate);
      }
    

    constructor(renderer: Renderer, el: ElementRef) {}
    
    ngOnChanges(...) {
      // inputs are updated
    }
    
    ngOnInit() {
      // executes after ngOnChanges was called the first time
      console.log(this);
      console.log(this.myDate);
      this.delta = (this.myDate);
    }