Bryan Bryan - 1 month ago 6x
Javascript Question

Seperate Directive Scope Angular2

I've tried looking at some similar questions here at SO but couldn't find a way to solve my problem.

There's a countdown @Directive() that takes in a couple inputs and counts down. The counting down part works, except I'm running into a problem where all the selectors are running / emitting the same numbers before going onto the next countdown. How would I get them to seperately countdown using their own parameters and running concurrently?


run() code in app.component.ts

run() {
var _this = this;
var counting = 0;
var incrementFactor = 0;
var increment = 1;

if (!isNaN(_this._duration) && !isNaN(_this._step) && !isNaN(_this._countFrom) && !isNaN(_this._countTo)) {
counting = Math.round(_this._countFrom);
incrementFactor = Math.round(Math.abs(_this._countTo - _this._countFrom) / ((_this._duration * 1000) / _this._step));
increment = (incrementFactor < 1) ? 1 : incrementFactor


_this._timer = setInterval(function() {
if (_this._countTo < _this._countFrom) {
if (counting <= _this._countTo) {
} else {
counting -= increment;
}, _this._step);


The problem is with your component. You used the same variable 'counting' for all 3 directives.

It works if you use 3 different component level variables as follows:

Here is an updated version of your plunk

    selector: 'my-app',
    template: `
    <countDown [step]="100" [countFrom]="100" [countTo]=0 [duration]="2" (countToChange)="count1 = $event">{{ count1 }}</countDown>
    <countDown [step]="100" [countFrom]="1000" [countTo]=0 [duration]="4" (countToChange)="count2 = $event">{{ count2 }}</countDown>
    <countDown [step]="100" [countFrom]="10000" [countTo]=0 [duration]="20" (countToChange)="count3 = $event">{{ count3 }}</countDown>
    directives: [countDown]
export class AppComponent {
  public count1:number;
  public count2:number;
  public count3:number;