Skip to main content

Dynamic three column layout using Structural Directive in Angular 7 and Material UI based application


Recently I came across a requirement in which I had to implement a multi-column layout with Dynamic Data. At several places I had to present the data into two columns and at some other places in three or even four columns. But one thing was common which was my input. My input was always an array of some kind of objects.

The application I was writing was an Angular7 based dashboard application with lots of different ways of presenting data. I used Material UI for theming and fontaewsome for icons.

I had to present data in column layout similar to the following



In some other places I had to break data into 3 or 4 columns. Plus the layout was different at all places. For example as in the following screenshot.


There were several other places where I had to do the same but use different UI elements, colors and designs.

My only option for all such screen was to either write a recursive template for each of them or use a nested loop e.g a nested *ngFor all these screens. I found myself repeating a code like the following


<div class="col col-md-1" ngfor="let sublistIndex of [[0, list.length/2+1], [(list.length/2)+1, list.length]]">
<mat-accordion ngfor="let item of list.slice(sublistIndex[0],sublistIndex[1]);">
 <mat-expansion-panel>
   <mat-expansion-panel-header class="heading">
       {{item.title}}
   </mat-expansion-panel-header>
 </mat-expansion-panel>
</mat-accordion>
I had a different template for every place but the first line of code was essentially providing me indices to break the list into sublists. I always had to equally divide the list into sublists for all columns. In cases where number of items in list can be divided fully by number of columns, without any remainder I had to display equal number of items in all column and where there was a remainder the last column should hold extra items.

I had options to write code into my controller and repeat for every component or find a generic way to do this. I ended up with an Structural directive called *sublist. Following is the implementation of directive.

import {Directive, Input, TemplateRef, ViewContainerRef, DoCheck } from '@angular/core';

@Directive({
  selector: '[sublist][sublistOf][sublistNumberOfColumns]'
})
export class SublistDirective implements DoCheck {
  private list: any;
  private isDirty = false;
  private numberOfColumns = 1;

  @Input()
  set sublistOf(sublistOf: any) {
    this.list = sublistOf;
    this.isDirty = true;
  }

  @Input()
  set sublistNumberOfColumns (sublistNmberOfColumns: number) {
    this.numberOfColumns = sublistNmberOfColumns;
  }

  constructor(private container: ViewContainerRef,
              private template: TemplateRef) { }

  ngDoCheck(): void {
    if (this.isDirty) {
      this.isDirty = false;
      this.container.clear();
      const itemsInSublists = Math.floor(this.list.length / this.numberOfColumns);
      for (let i = 0, j = 0; i < this.numberOfColumns; i++) {
        const subList = i === this.numberOfColumns - 1 ? this.list.slice (j) : this.list.slice(j, itemsInSublists + j) ;
        this.container.createEmbeddedView(this.template, {$implicit: subList});
        j = j + itemsInSublists;
      }
    }
  }
}
So now I don't have to repeat my code anywhere and I just have to add one directive in my html anywhere, where I have to break the list to display in columns

<div class="col col-md-1" *sublist="let sublist of list; numberOfColumns: '2'">
<mat-accordion ngfor="let item of sublist">
      <mat-expansion-panel>
          <mat-expansion-panel-header class="heading">
              {{item.title}}
          </mat-expansion-panel-header>
        </mat-expansion-panel>
      </mat-accordion>
</div>

Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Difference between ng-template, ng-content and ng-container

While working on a very complex feature for a client in which I had to present hierarchical dynamic data in three column layout with ability to expand like google image search on each level, I came across ng-content, which seemed like a perfect fit for the solution I was thinking about implementing. But I got confused between ng-content and ng-container when I saw the generated html while debugging my code in developer console. I further investigated both ng-content and ng-container and decided to write my finding here in my blog for future references. If you are also wondering what are they for, read on. <ng-container> When you have to write different host elements to combine many structural component like the following <div *ngIf="condition"> <div *ngFor="..."> Some content here </div> </div> You get many unintentional host elements which are not required for your layout. It becomes a prolem when you have complex appl...

Angular 2+: ng-content

Have you ever felt the need of writing a component like the following <my-component> <div> Some text here </div> <div> Some text here </div> <div> Some text here </div> <div> Some text here </div> </my-component> Now your intention here is to have your custom component and keep having the additional html that you have written between statring and ending tags. If yes, then you are on the right place. Angular provides an element called ng-content which can used to write configurable components. This is called Component Projection, neaning the content that will be procvided inside the opening and closing brackets will be projected. It will be rendered inside a <ng-content> element. It means that you must include a <ng-content> tag somewhere in your components html template so that the provided content can be projected inside it. So your my-component should have a template like the following // myCompo...