作者:victor | 来源:互联网 | 2022-12-09 17:07
与Google登录页面类似,单击事件后,我希望自动聚焦于输入元素。我尝试了@ViewChild('id')和document.getElementId('id')。两者都不起作用。它始终为null或未定义。我该如何实现?
smnbbrv..
6
不幸的是,所有其他解决方案在渲染时均无法与自动对焦的matInput一起使用。
原因是应该使用matInput的高级api而不是尝试集中输入本身。
应该做的是打电话给matInput.focus()
。这是使用此方法的简单指令:
import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material';
@Directive({
selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {
constructor(private matInput: MatInput) { }
ngOnInit() {
setTimeout(() => this.matInput.focus());
}
}
需要超时才能延迟对元素的聚焦,因为matInput在创建时仍无法正常运行。用法:
当然,命名选择器matInputAutofocus
是很危险的,因为材料本身可能有一天会出现在此解决方案中。使用它需要您自担风险,或仅使用前缀重命名(推荐)。
1> smnbbrv..:
不幸的是,所有其他解决方案在渲染时均无法与自动对焦的matInput一起使用。
原因是应该使用matInput的高级api而不是尝试集中输入本身。
应该做的是打电话给matInput.focus()
。这是使用此方法的简单指令:
import { Directive, OnInit } from '@angular/core';
import { MatInput } from '@angular/material';
@Directive({
selector: '[matInputAutofocus]',
})
export class AutofocusDirective implements OnInit {
constructor(private matInput: MatInput) { }
ngOnInit() {
setTimeout(() => this.matInput.focus());
}
}
需要超时才能延迟对元素的聚焦,因为matInput在创建时仍无法正常运行。用法:
当然,命名选择器matInputAutofocus
是很危险的,因为材料本身可能有一天会出现在此解决方案中。使用它需要您自担风险,或仅使用前缀重命名(推荐)。