indra257
indra257

Reputation: 86

Angular2: displaying items in row/column fashion

I have an array with the below format, where first parameter is the text to be displayed, second is the column number and third is the row number. I want to display these items based on their column and row location.

[[ "a",  "0", "0"],
["b", "0", "1"],
["c", "0", "2"],
["d", "1", "0"],
["e", "1", "1"],
["f", "2", "0"],
["g", "2", "1"]

]

Desired Output:

a d f
b e g
c

Upvotes: 0

Views: 667

Answers (2)

YounesM
YounesM

Reputation: 2317

You can do it like this : Plunker

Component :

  value : string;
  rows : any[];
  cols : any[];
  arr : any = [[ "a",  "0", "0"],
    ["b", "0", "1"],
    ["c", "0", "2"],
    ["d", "1", "0"],
    ["e", "1", "1"],
    ["f", "2", "0"],
    ["g", "2", "1"]];

  constructor() { 
    this.rows = Array(3).fill();
    this.cols = Array(3).fill();
  }

  activeElement(r,c) : string{
    for(let elem of this.arr){
      if(parseInt(elem[1]) === c && parseInt(elem[2]) === r){
        console.log(true);
        return elem[0];
      }
    }
    return ""
  }

Template :

<div *ngFor="let row of rows; let rowId = index">
 <span *ngFor="let col of cols; let colId = index">
   {{activeElement(rowId,colId)}}
 </span>
</div>

Upvotes: 1

Martin
Martin

Reputation: 16302

You will want to look at flex box Flex Box.

Essentially you will want to use a column based layout that wraps.

Additionally, there is a component library for Angular to declarative help with this: FlexLayout

Using FlexLayout you would do something like this:

@Component({
  template: `
    <div fxFlexLayout="column" fxLayoutWrap>
      <div fxFlex="30%" *ngFor="let item of items | async">{{ item }}</div>
    </div>
  `
})
export class ItemListComponent implements OnInit {

    items: Observable<Item[]>

    constructor(...) {}

    ngOnInit() {
       this.items = this.service.getItems()
         .map(x => x.[0])
    }

}

Upvotes: 0

Related Questions