Angular 将光标放在焦点|角度2上输入字段值的末尾
我创建了一个动态组件,并在Angular 将光标放在焦点|角度2上输入字段值的末尾,angular,typescript,Angular,Typescript,我创建了一个动态组件,并在ngAfterViewInit上完成了以下代码: setTimeout(() => { this.input.nativeElement.focus(); }, 0); 这是可行的:它正确地将焦点设置在输入上,但光标放在值的开头。我想将光标放在值的末尾 我试过这个: setTimeout(() => { this.input.nativeElement.focus(); let start = this.input.nativeElement.
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;
@ViewChild('input')输入:ElementRef;
有什么想法吗?当使用角度反应形式时,它是开箱即用的。这是
也似乎是开箱即用。然而,角度反应形式无论如何都是一种幸福。是您的输入元素
FormControl
还是ngModel
?它不是ng model然后FormControl
?对于我来说,这是一种开箱即用的工作方式,没有任何混乱:
,我使用@ViewChild('input')输入访问:ElementRef代码>谢谢!我修改了我的组件以使用form builder,现在可以使用了
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();
}
}
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();
}
}