Varun Nuthalapati Varun Nuthalapati - 1 year ago 121
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 :

Angular 2 Code (should be fixed):

html code:

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

JS code:

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 Source

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


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

TypeScript Code

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

export class ProgressBar{
    progressPercentage: number;

    constructor() {
      this.progressPercentage = 50;