我有一个正在创建的动态组件,在 ngAfterViewInit
上我已经完成了以下代码:
setTimeout(() => {
this.input.nativeElement.focus();
}, 0);
这有效:它正确地将焦点设置在输入上,但光标位于值的开头。我想将光标放在值的末尾。
我已经试过了:
setTimeout(() => {
this.input.nativeElement.focus();
let start = this.input.nativeElement.selectionStart;
let end = this.input.nativeElement.selectionEnd;
this.input.nativeElement.setSelectionRange(start,end);
}, 0);
我也试过清除值并重置它,但无法让它工作。
这是 html 以及我如何访问它:
<input class="nav-editor__input" #input type="text">
@ViewChild('input') input: ElementRef;
有什么想法吗?
最佳答案
当使用 Angular Reactive Forms 时,它开箱即用。这是 example .
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<h1>Focus Test!</h1>
<input #testInput type="text" [formControl]="formCtrl">
`
})
export class AppComponent implements OnInit, AfterViewInit {
name = 'Angular';
@ViewChild("testInput") testInput;
formCtrl = this.fb.control('');
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.formCtrl.setValue('Test');
}
ngAfterViewInit() {
this.testInput.nativeElement.focus();
}
}
在 ngAfterViewInit()
中设置焦点,将光标置于输入值的末尾。
这里是 example没有反应形式。
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>Focus Test!</h1>
<input #testInput type="text" [value]="value">
`
})
export class AppComponent implements OnInit, AfterViewInit {
name = 'Angular';
value = '';
@ViewChild("testInput") testInput;
constructor() {}
ngOnInit() {
this.value = 'Test';
}
ngAfterViewInit() {
this.testInput.nativeElement.focus();
}
}
似乎也开箱即用。然而,Angular Reactive Forms 无论如何都是一种幸福。
关于angular - 将光标放在焦点上输入字段值的末尾 | Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53843529/