So I’ve been experimenting with Angular 2 recently and came across a problem that I decided was worth sharing the solution of.
Imagine you want to build an Angular 2 component that needs to have two input properties passed down.

<number-count [total]="product.price" duration="3000"></number-count>  

If you are wondering why I'm using brackets for passing down the total that is because product.price is a property. Duration however isn't and thus doesn't need brackets.
If we want to use these properties in the component view, all we need is to declare an input property in the component class.

@Input() total;
@Input() duration;

Now we're able to use them in the view.

 template:`
    <p>{{total}}</p>
  `

However if we want to use these properties in the component class itself, we can only use them inside the following function:

ngAfterViewInit() {  
  this.interval = setInterval(this.incrementValue.bind(this), parseInt(this.duration) / this.total);
}

We can only access them in this function because the input properties are only filled in after the view is initialized.
The whole component looks something like this:

import {Component, Input} from 'angular2/core';  
import {CORE_DIRECTIVES} from 'angular2/common';

@Component({
  selector: 'number-count',
  directives: [ CORE_DIRECTIVES ],
  template:`
    <p>{{count}}</p>
  `
})
export class NumberCount implements AfterViewInit {  
  @Input() total;
  @Input() duration;
  private count: number = 0;
  private interval: any;

  ngAfterViewInit() {
    this.interval = setInterval(this.incrementValue.bind(this), parseInt(this.duration) / this.total);
  }

  incrementValue() {
    if (this.count < this.total) {
      this.count += 1;
    }
    else {
      clearInterval(this.interval);
    }
  };
}
Author image
Tom Buyse
My name is Tom Buyse. I work for Bewire in Belgium. My primary focus is front-end development, which currently mostly involves Angular, Angular 2 and Ionic.
comments powered by Disqus