binoculars
binoculars

Reputation: 2274

Dynamic variables in angular2 / javascript

I have multiple download buttons on a page, with a progress bar for each download:

<progress-bar *ngIf="progressbar" [progress]="loadProgress_id1"></progress-bar>
<progress-bar *ngIf="progressbar" [progress]="loadProgress_id2"></progress-bar>

...

I have a function that sets the progress:

setpercentage(perc,id) {
    this.loadProgress_+id = Math.round(perc); // --> how could I do this?
    this.ref.detectChanges();
}

What I've tried (the above) doesn't work. How could I achieve this? Or should I use a different approach?

Upvotes: 2

Views: 95

Answers (2)

Jess
Jess

Reputation: 90

Is there any reason an array wouldn't work for this?

// Html

<progress-bar 
  *ngFor="let progress of progressBars" 
  [progress]="progress"
></progress-bar>

// Ts

progressBars: number[] = [0,0];

setpercentage(perc,id) {
  this.progressBars[id] = Math.round(perc);
  this.ref.detectChanges();
}

Upvotes: 1

Tiep Phan
Tiep Phan

Reputation: 12596

try this

setpercentage(perc,id) {
    this['loadProgress_' + id] = ....
}

or

setpercentage(perc,id) {
    const prop = 'loadProgress_' + id;
    this[prop] = ...
}

Upvotes: 1

Related Questions