Angular 10 プロジェクトには、ユーザー名とパスワードという名前の 2 つの入力を持つフォームがあります。使っています
ユーザー名フィールドの cdkFocusInitial 属性ですが、ページの読み込みには焦点を当てていません。この問題を示す StackBlitz の例は次のとおりです https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
<div class="example-focus-monitor">
<mat-form-field appearance="fill">
<mat-label>Username</mat-label>
<input cdkFocusInitial aria-label="Username" class="username"
matInput
placeholder="Enter Username" type="text">
</mat-form-field>
<br/>
<mat-form-field appearance="fill">
<mat-label>Password</mat-label>
<input aria-label=" Password" class="password" matInput placeholder="Enter Password"
type="text">
</mat-form-field>
</div>
[1]: https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
------------------------
最初の div に追加:
cdkTrapFocus [cdkTrapFocusAutoCapture]="true"
https://stackblitz.com/edit/angular-4amzj4-nz2yh4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
2
3
モジュールのインポートに A11yModule を追加する必要があります
– パヴァン・ジャッダ
2020 年 9 月 11 日 14:39
Stackblitz の代わりに (加えて) ここにコードがないのはなぜでしょうか。コード行数はそれほど多くありません
– モジタバ
8 月 8 日2023 年 8 時 58 分
------------------------
これは、cdkFocusInitial が FocusTrap のコンテキストで使用されるためです。ここでそれについて読むことができます。
オートフォーカスを実行するには、要素の参照を取得してフォーカスするディレクティブを作成できます。
import { AfterContentInit, Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autoFocus]"
})
export class AutofocusDirective implements AfterContentInit {
@Input() public appAutoFocus: boolean;
public constructor(private el: ElementRef) {}
public ngAfterContentInit() {
setTimeout(() => {
this.el.nativeElement.focus();
}, 100);
}
}
このディレクティブは次のように使用します
<input
autoFocus
aria-label="Username"
class="username"
matInput
placeholder="Enter Username"
type="text"
>
これをページ上で複数回使用すると、最後に使用したものがフォーカスされます。
乾杯!
2020 年 9 月 4 日 22:59 に回答
ラクシット シン ラワット
ラクシット シン ラワット
156
6
6 ブロンゼバッジ
2
1
他に何も機能させることができませんでしたが、これは見事に機能しました。ありがとう
– ジョン・ギルマー
2023 年 1 月 24 日 1:07
これは機能しますが、ディレクティブでは何も行われない @Input() appAutoFocus を削除する必要があります。そこにある理由はありますか?
– LeO
2023 年 4 月 17 日 10:25