不幸的是,并非每个解决方案都能在渲染时始终与自动对焦 matInput 配合使用。这是我尝试过的:
- HTML
autofocus
属性
- JS
input.focus()
-
cdkFocusInitial
from @angular/cdk
上述所有方法都可能有效,但在某些情况下它们似乎会被破坏。
What 始终如一地 and always作品正在使用高级 APImatInput
。这是使用这种方法的简单指令:
import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material/input';
@Directive({
selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {
constructor(private matInput: MatInput) { }
ngOnInit() {
setTimeout(() => this.matInput.focus());
}
}
需要超时来延迟聚焦元素,因为 matInput 在创建时尚未正常运行。用法:
<mat-form-field>
<input type="text" matInput matInputAutofocus>
</mat-form-field>
当然,命名选择器matInputAutofocus
是危险的,因为材料本身有一天会得出这个解决方案。使用它需要您自担风险,或者仅使用您的前缀重命名(推荐)。
聚焦并同时选择输入值
锦上添花的是添加了预选择输入内容的可能性(这在大多数情况下更加用户友好),这稍微改变了实现:
import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material/input';
@Directive({
selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {
@Input()
autofocusSelectValue = false;
constructor(
private matInput: MatInput,
private elRef: ElementRef<HTMLInputElement>,
) { }
ngOnInit(): void {
setTimeout(() => {
this.matInput.focus();
if (this.autofocusSelectValue) {
this.elRef.nativeElement.setSelectionRange(0, this.elRef.nativeElement.value.length);
}
});
}
}
将其用作:
<mat-form-field>
<input type="text" matInput matInputAutofocus [autofocusSelectValue]="true">
</mat-form-field>