如何获得父div的宽度并基于在angular2中进行进一步的操作

时间:2017-11-14 19:05:26

标签: angular

在这里,我希望得到#divToMeasure的宽度,然后基于此,需要做进一步的操作。 请帮助我修复此代码,并且总是欢迎更好的方法或建议。

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);
}

1 个答案:

答案 0 :(得分:0)

我相信这就是你要找的东西。

abc.component.ts

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

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

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