Search code examples
htmlcssangularcss-gridng-style

Angular - How to pass object dynamically to div element using [ngstyle]


I'm trying to make grid-row and grid-column to be dynamically populated from API.

component.html

<div *ngFor = "let element of elements">
   <div [ngStyle]="styleObject(element.Row,element.Column)">{{element['Tool Name']}}</div>
</div>

component.ts

styleObject(row : String,Column:String): Object {
    let obj :Object;
    obj = {'grid-row':''+Number(row),'grid-column':''+Number(Column)};
    console.log(obj);
    return obj.toString;
}

This way in the console it is printing but it's not reflecting in UI. Console Image

It worked properly when I tried to populate the data manually as

<div [ngStyle]="{'grid-column':'9','grid-row':'9'}">{{element['Tool Name']}}</div>

In the Inspect Element mode, the attribute is showing as enter image description here

Where am I making mistake? Thanks in advance.


Solution

  • According to NgStyle docs,

    Set a collection of style values using an expression that returns key-value pairs.

    <some-element [ngStyle]="objExp">...</some-element>
    

    You need to return styleObject as key-value pair type instead of string type.

    styleObject(row : String, Column:String): Object {
      let obj :Object;
      obj = {'grid-row':''+Number(row),'grid-column':''+Number(Column)};
      return obj;
    }
    

    You may check out this sample demo.


    Updated for grid layout issue

    For your grid layout, should have .grid-container and .grid-item.

    .grid-container

    Wrap the whole div element and turn it to the grid.

    .grid-item

    The grid item with [ngStyle] have to place here so that it will be positioned based on grid-row and grid-column.


    component.html

    <div class="grid-container">
      <div *ngFor="let element of elements" class="grid-item" 
        [ngStyle]="styleObject(element.row, element.column)">
        {{element['name']}}
      </div>
    </div>
    

    .component.css

    .grid-container {
      display: grid;
      grid-row-gap: 50px;
      grid-template-columns: auto auto auto;
      justify-content: center;
      background-color: #2196F3;
      padding: 10px;
    }
    
    .grid-item {
      background-color: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(0, 0, 0, 0.8);
      padding: 20px;
      font-size: 30px;
      text-align: center;
    }
    

    Sample Grid Layout on StackBlitz