angularangular5angular-material-5

Angular 5: clicked button that triggers a dialog becomes highlighted after the dialog is closed


I noticed that button gets classes cdk-focused and cdk-program-focused added after the dialog it triggered is closed. If I click anywhere effect disappears.

app.component.html [fragment]

<mat-cell *matCellDef="let element">
  <span matTooltip="Delete" matTooltipPosition="right">
    <button mat-icon-button color="warn" (click)="openDeleteAssociationDialog()">
      <mat-icon>delete</mat-icon>
    </button>
  </span>
</mat-cell>

Illustration


Solution

    1. Add to your button in HTML some id. In my case it's #changeButton:
    <button #changeButton mat-icon-button (click)="changeItem(element)" disableRipple>
        <mat-icon>edit</mat-icon>
    </button>
    
    1. Import ViewChild and ElementRef in the .ts file:
    { ViewChild, ElementRef } from '@angular/core';
    
    1. Declare a new variable in the .ts file:
    @ViewChild('changeButton') private changeButton: ElementRef;
    
    1. Subscribe to your dialog's afterClose() event and remove the cdk-program-focused css class:
    dialogRef.afterClosed().subscribe(result => {
        this.changeButton['_elementRef'].nativeElement
            .classList.remove('cdk-program-focused');
    }