DEV Community

John Peters
John Peters

Posted on

Material Tab Styling in Angular for a CSS Tool

Angular's View Encapsulation design, sometimes makes it almost impossible to write a style for Material components. One of them is the mat-tab.

 <mat-tab-group>
   <mat-tab  *ngFor="let item of data; index as i" [label]="i">
    <ng-template mat-tab-label>
      <div class='mytabstyle'>
      {{i}}
      </div>
    </ng-template>
     <div class='margin1em'>
        // Your content here for each item
     </div>
   </mat-tab>
 </mat-tab-group>
Enter fullscreen mode Exit fullscreen mode

Change the mat-tab-labels display style.

  ngAfterViewInit() {
    let mt = 
    (document.getElementsByClassName('mat-tab-labels'))[0] as HTMLElement;
    mt.style.display='grid';
    mt.style.gridTemplateColumns='repeat(auto-fit, minmax(3em, 1fr))'
  }
Enter fullscreen mode Exit fullscreen mode

We use the now famous HTML5 grid, setting each tab width to 3em.

Here's the tab template CSS class 'mt'

.mt {
    align-items: center;   
    box-shadow: 0px 1px 1px inset midnightblue;
    box-sizing: border-box;
    cursor: pointer;
    display: grid;
    grid-template-columns: 3em;
    height: 27px;
    justify-content: center;
    opacity: 0.6;
    white-space: nowrap;
}
Enter fullscreen mode Exit fullscreen mode

It's a good start, but there's still some work to do on the selected tab underline... Note we did not parse a single style sheet, it was already done by the browser, we just pulled the parsedText to display here.

csslexer

JWP2020 CSS parser
JWP2020 Material Tabs

Top comments (0)