Angular – How to disable or overwrite cdk-focused in Angular

angularangular-cdkangular-material

I am working on mat-button-toggle-group for which I modified existing css by overwriting mat-button-toggle-checked class like below. Now, when I toggle between buttons the css is not working till I get focus out and that is because 2 cdk classes 'cdk-focused' and 'cdk-program-focused' are being added when the clicked button is on focus . Is there any way that I can make these classes disable or make them not apply or overwrite them with same css of mat-button-toggle-checked?

<mat-button-toggle-group #group="matButtonToggleGroup" value="line">
    <mat-button-toggle (click)="showLine()" value="line">Line</mat-button-toggle>
    <mat-button-toggle (click)="showChart()" value="chart">Chart</mat-button-toggle>
</mat-button-toggle-group>

and css

mat-button-toggle-group {
    border: solid 1px #d1d8de;
    width:260px;
    height:41px;
    text-align: center;
    .mat-button-toggle-checked{
      background-color: #ffffff;
      font-weight: bold;
    }
    .mat-button-toggle{
      width:50%;
      font-size: 15px;
    }
  }

Best Answer

You can make use of Angular CDK's FocusMonitor service to disable .cdk-focused and .cdk-program-focused classes by calling the service's stopMonitoring() method.

The documentation for this & the API can be found in the following links respectively:
1) FocusMonitor documentation &
2) FocusMonitor API

The problem I had:

My sidenav had 4 buttons created using *ngFor. Each of these buttons was also a routerLink. Only the button whose router link was active should have primary background color.

Now, this was getting confusing if, say, the routerLink associated with my 4th button was active as the 4th button would have the primary background color and the 1st button had focused styling because of .cdk-focused and .cdk-program-focused classes applied by the FocusMonitor on the button.

The solution:

import { Component, AfterViewInit } from '@angular/core';
import { FocusMonitor } from '@angular/cdk/a11y';

@Component({
    selector   : 'test-component',
    templateUrl: 'test-component.template.html',
})

export class TestComponent implements AfterViewInit {
    constructor(private _focusMonitor: FocusMonitor) {}

    ngAfterViewInit() {
        this._focusMonitor.stopMonitoring(document.getElementById('navButton_1'));
    }
}

You can take a look at the documentations for tailoring this to your need.