Skip to main content Skip to footer

Dynamically Resize FlexGrid to fit Host Element in Angular

Background:

By default, FlexGrid will not resize itself when the size of the window or element that contains it changes size. We can use FlexGrid's hostElement property to get the size of the grid's host element and change the grid's size when the host element gets changed.

Steps to Complete:

1. Get the height and width of FlexGrid's host element

2. Trim off some of the size so that it doesn't entirely fill the host element

3. Splice 'px' back into the new height and width values

4. Assign these new height and width values to the host element of FlexGrid, causing it to automatically resize

Getting Started

Get the height and width of FlexGrid's host element

First, we'll need to get the height and width of the element containing FlexGrid. In this case, we're putting the FlexGrid inside of a dialogue, so we'll need the size of the dialogue.

splitStringHeight = this.mainDialogue.content.style.height.split("p");
splitStringWidth = this.mainDialogue.content.style.width.split("p");

This will create two arrays that each have two objects; a numeric value for the width/height in pixels and a string value of 'px'.

Trim off some of the size so that it doesn't entirely fill the host element

Now that we have the numeric value for the width/height of the host element, we need to trim some of the size off to prevent it from filling the entire element. 

currentHeight = +splitStringHeight[0];
newHeight = currentHeight - 10;
currentWidth = +splitStringWidth[0];
newWidth = currentWidth - 10;

Before inserting the values back into the grid's host element style properties, the 'px' value needs to be appended back onto the height/width values so that the application knows that we're using pixels to set the width. 

pixelHeight = newHeight.toString() + "px";
pixelWidth = newWifth.toString() + "px";

Assign these new height and width values to the host element of FlexGrid, causing it to automatically resize

Finally, we assign these values to the hostElement style of FlexGrid. We claos add a little bit of padding to five a little bit more space around the edge. 

this.mainGrid.hostElement.style.height = pixelHeight;
this.mainGrid.hostElement.style.width = pixelWidth;
this.mainGrid.hostElement.style.padding = '5px';

You can also find a live sample of this project at this location: https://stackblitz.com/edit/wijmo-knowledgebase-angular-flexgrid-dynamic-size

Joel Parks