Varun Nuthalapati Varun Nuthalapati - 4 months ago 58
Javascript Question

Access DOM Properties in Angular 2

I've implemented a progress bar and displayed the percentage of progress bar in the html by accessing the width property of the progress bar using document.getElementsByClassName . But what should i use to implement this in Angular 2, which uses typescript.

Working HTML and JS code : https://jsfiddle.net/nvarun123/2cy2kg7y/1/

Angular 2 Code (should be fixed): https://plnkr.co/edit/nlRa0aaQv7GntxxBy8AC?p=preview

html code:

<div class="container">
<div class="bar">
<span class="bar-fill"></span>
</div>
</div>
<div id="progress"></div>


JS code:

var
bar = document.getElementsByClassName("bar")[0],
barFill = document.getElementsByClassName("bar-fill")[0],
progress = document.getElementById("progress"),
barWidth = window.getComputedStyle(bar, null).getPropertyValue("width"),
barFillWidth = window.getComputedStyle(barFill, null).getPropertyValue("width"),
pct = 100 * (parseFloat(barFillWidth) / parseFloat(barWidth)) + "%";

progress.innerHTML = pct;

Answer

I would use ngStyle so you could dynamically update the progress bar percentage and display to the users.

HTML Code

<div class="container">
  <div class="bar">
    <span class="bar-fill" [ngStyle]="{'width': progressPercentage + '%'}">
    </span>
  </div>
</div>
<div id="progress">{{progressPercentage}}%</div>

TypeScript Code

import {Component} from '@angular/core';
@Component({
    selector:'progressbar',
    styleUrls: ['./progressbar.component.css'],
    templateUrl: './progressbar.component.html'

})
export class ProgressBar{
    progressPercentage: number;

    constructor() {
      this.progressPercentage = 50;
    }
}

plunkr https://plnkr.co/edit/LytbNF5HdDYUAxBUYenf?p=preview