Angular 5:点击触发对话框的按钮在对话框关闭后高亮显示

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

我注意到按钮 类 添加了 cdk-focused 和 cdk-program-focused 它触发的对话框关闭之后。如果我点击任何地方,效果就会消失。

app.component.html [片段]

<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>

  1. 将一些 ID 添加到 HTML 中的按钮。在我的例子中是 #changeButton:
<button #changeButton mat-icon-button (click)="changeItem(element)" disableRipple>
    <mat-icon>edit</mat-icon>
</button>
  1. 在 .ts 文件中导入 ViewChild 和 ElementRef:
{ ViewChild, ElementRef } from '@angular/core';
  1. 在 .ts 文件中声明一个新变量:
@ViewChild('changeButton') private changeButton: ElementRef;
  1. 订阅对话框的 afterClose() 事件并删除 cdk-program-focused css class:
dialogRef.afterClosed().subscribe(result => {
    this.changeButton['_elementRef'].nativeElement
        .classList.remove('cdk-program-focused');
}

就我而言,真正的问题在于按钮结构,'material' 构建各种子组件,最后一个是 'div' 和 css class 'mat-button-focus-overlay':

我的解决方案很简单,在 'style.css' 文件中,添加或改写 'mat-button-focus-overlay'

.mat-button-focus-overlay { background-color: transparent!important; }

这种风格适合我:

.mat-button, .mat-flat-button, .mat-stroked-button
{   
    &.cdk-program-focused .mat-button-focus-overlay
    {
        opacity: 0 !important;
    }
}

您可以简单地覆盖 mat-dialog 使用文件

中的 css
.mat-button-focus-overlay { 
  background-color: transparent!important;
 }

在您的情况下,将此 css 添加到 mat-cell 组件的 css 文件中。

这样使用

        .mat-icon-button,
        a.mat-button {
            &.cdk-focused,
            &.cdk-program-focused {
                background-color: transparent;
    
                .mat-button-focus-overlay {
                    display: none;
                }
            }
        }

基于@yuzhou,我发现一些按钮仍然保留了某种形式的焦点。我没有删除 类,而是在元素上调用模糊,这解决了我的问题。

dialogRef.afterClosed().subscribe(result => {
    this.changeButton['_elementRef'].nativeElement.blur(); 
}

这里更好的解决方案是使用配置 属性 restoreFocus: false

matDialog.open(<your-component>, {
    restoreFocus: false
});

在这种情况下,当您使用 matDialogRef.close() 关闭 matDialog 时,焦点将不会应用于该删除 button/icon。

参考:https://github.com/angular/components/issues/8420 - 它还有其他替代解决方案,包括 restoreFocus: false