0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angularでデフォルト キャンセルを選択しているダイアログを表示

Posted at

概要

Angular Materialを使用していて、削除の確認を求めるダイアログを表示しているとき
Enterボタンなど連打してしまっても、うっかり削除しないように、デフォルトでキャンセルボタンにフォーカスを当てたい

環境

  • @angular/core 13.1.1
  • @angular/cdk 13.1.1

Point

Angular Material CDK の Accessibilityを使用

ダイアログ サンプル

  • どちらもフォーカスされていない状態

  • はいボタンにフォーカスされている状態(今回は使いません)

  • いいえボタンにフォーカスされている状態

ダイアログ表示時に、「いいえ」にフォーカスされていると、Enter連打されても、誤って削除を防げます。

準備

  • app.module.tsにCDKの A11yModule を追加
app.module.ts
+ import { A11yModule } from '@angular/cdk/a11y';

@NgModule({
  imports: [
+    A11yModule,
  ],
})

1. 変更前ダイアログ

  • HTMLだけで実装できるので、ts側のコードは省略します。
dialog.component.html
<h1 mat-dialog-title="">削除します。よろしいですか?</h1>
<mat-dialog-actions fxLayout="row" fxLayoutAlign="space-between">
  <button [mat-dialog-close]="true" color="warn" mat-raised-button="">
    <mat-icon>delete</mat-icon>
    はい
  </button>
  <button [mat-dialog-close]="false" mat-raised-button="">
    <mat-icon>close</mat-icon>
    いいえ
  </button>
</mat-dialog-actions>

これだと、ダイアログは、どのボタンにもフォーカスが当てられていない状態で表示されます。

2. 変更後ダイアログ

dialog.component.html
 <h1 mat-dialog-title="">削除します。よろしいですか?</h1>
+ <mat-dialog-actions fxLayout="row" fxLayoutAlign="space-between" cdkTrapFocus [cdkTrapFocusAutoCapture]="true">
+  <button [mat-dialog-close]="true" color="warn" mat-raised-button="" cdkFocusRegionStart>
    <mat-icon>delete</mat-icon>
    はい
  </button>
+  <button [mat-dialog-close]="false" mat-raised-button="" cdkFocusRegionEnd cdkFocusInitial>
    <mat-icon>close</mat-icon>
    いいえ
  </button>
 </mat-dialog-actions>
  • タブキーを押したときに、ダイアログ以外をフォーカスしないようにするために、cdkTrapFocus を追加
  • はい・いいえ ボタンのふたつだけフォーカスの範囲なので、cdkFocusRegionStartcdkFocusRegionEnd を追加
  • いいえボタンが、フォーカスの起点なので、いいえボタンにcdkFocusInitialを追加
  • cdkFocusInitialを使用するときは、[cdkTrapFocusAutoCapture]="true"になっていないといけないようので、cdkTrapFocusと同じタグに[cdkTrapFocusAutoCapture]="true"を追加

上記の変更を行うと、ダイアログ表示時、デフォルトでいいえにフォーカスが当たっている状態になりました。

参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?