通过循环Javascript计算总高度

时间:2017-04-18 10:04:47

标签: javascript angular typescript ag-grid

嗨我有一个包含n行的表。我需要根据行高来计算总高度。以下是Typescript代码:

private _getRowHeight(_params: any): number {
    let totalRowHeight: number;
    let maxHeight: number = 100;
    let contentLength: number = 50;
    for (let i in _params.data) {
        if (i != "time" && _params.data[i] instanceof Array) {
            let tempHeight: number = 100 * _params.data[i].length;
            if (tempHeight > maxHeight) maxHeight = tempHeight;
            for (let x in _params.data[i]){
                let tempContentHeight: number = 20 * _params.data[i][x].content.length;
                if (tempContentHeight > contentLength) contentLength = tempContentHeight;
            }
        }
    }
    maxHeight += contentLength;
    return maxHeight;
}

基本上,maxHeight是每行的高度。如何计算每行maxHeight或每行的高度之和,并将其分配给变量totalRowHeight。请指教。在此先感谢你们

1 个答案:

答案 0 :(得分:1)

假设每行的高度没有固定(在这种情况下只需一个简单的arrayOfRows.length * x),那么你可以使用ElementRefoffsetHeight来获得高度,即:

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

@Component({
   selector: 'table-example',
   template: '<table-example> ... </table-example>'
})
export class TableExampleComponent {

   totalRowHeight: number;

   constructor(private elRef: ElementRef) {}

   // make sure the view has been fully rendered with ngAfterViewInit

   ngAfterViewInit() { 
      let totalRowHeight = this.elRef.nativeElement.offsetHeight;
   } 
}