Angular 4 文本框自动获取焦点二
发布时间:2020-12-17 08:38:02 所属栏目:安全 来源:网络整理
导读:Angular是不推荐直接通过DOM操作获取元素的,要操作元素就通过@ViewChild装饰器。 在HTML中对元素添加引用myInput: input type = "text" #myInput 在ts中可以通过ViewChild获取指定元素的引用: import { ViewChild } from '@angular/core' ;@ViewChild( 'm
Angular是不推荐直接通过DOM操作获取元素的,要操作元素就通过@ViewChild装饰器。 在HTML中对元素添加引用myInput: <inputtype="text"#myInput>
在ts中可以通过ViewChild获取指定元素的引用: import { ViewChild } from '@angular/core';
@ViewChild('myInput') input;
获取到对应元素的引用后,你想添加焦点,如下: this.input.nativeElement.focus()
nativeElement获取的是原始DOM元素,至于你想在哪里自动获取焦点,就看你的业务逻辑了,可以配合Angular对应的生命周期使用。 这是在segmentfault上别人给我的答案。 我的业务需求是页面加载完毕就立马给input获取焦点; 所以用到了
ngAfterViewInit()
:
void {
this.
renderer.
invokeElementMethod(
this.
infocus.
nativeElement,'focus');
}
export class ModalDirective implements AfterViewInit,OnDestroy { ngAfterViewInit() { } ngOnDestroy() { } } 不然会报错 Implement lifecycle hook interface AfterViewInit for method ngAfterViewInit (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |