[Fixed] How to get width of a parent div and based on do further operations in angular2

Issue

Here, I want to get width of #divToMeasure and then based on this, need to do further operations.
Please, help me to fix this code and better approach or suggestion are always welcomed.

abc-component.html

<div #parentdiv class="col-xs-12 rmpm" style='width:100%;height:100%;'>
        <div #divToMeasure class="col-xs-12 rmpm"  [style.width.px]="parentdiv.offsetWidth">  <---get this 'width' in 'px'  
        </div>
        </div>

        <div *ngFor ='let dta of data; let i = index' [ngStyle]="{'width':WIDTH}">
         abc
        </div>

abc.component.ts

data = [1,2,3,4,5,6];
WIDTH: any

ngOnInit(){

// need to get the width of #divToMeasure 
let divToMeasureWidth = __________; <-------how to get that

this.WIDTH = (divToMeasureWidth / this.data.length);
}

Solution

I believe this is what you are looking for.

abc.component.ts

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({templateUrl: './abc-component.html'})
export class AbcComponent implements AfterInit {
  @ViewChild('divToMeasure') divToMeasureElement: ElementRef;

  ngAfterViewInit() {
    let divToMeasureWidth = this.divToMeasureElement.nativeElement.offsetWidth;
  }
}

Leave a Reply

(*) Required, Your email will not be published