cup*_*_of 6 typescript angular
我正在创建一个动态组件,并ngAfterViewInit完成了以下代码:
setTimeout(() => {
this.input.nativeElement.focus();
}, 0);
Run Code Online (Sandbox Code Playgroud)
这是有效的:它正确地将焦点设置在输入上,但光标放置在值的开头。我想将光标放在值的末尾。
我试过这个:
setTimeout(() => {
this.input.nativeElement.focus();
let start = this.input.nativeElement.selectionStart;
let end = this.input.nativeElement.selectionEnd;
this.input.nativeElement.setSelectionRange(start,end);
}, 0);
Run Code Online (Sandbox Code Playgroud)
我也尝试过清除该值并重置它,但无法让它工作。
这是 html 以及我如何访问它:
<input class="nav-editor__input" #input type="text">
@ViewChild('input') input: ElementRef;
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
当使用 Angular Reactive Forms 时,它可以开箱即用。这是示例。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
将焦点设置在 中ngAfterViewInit(),将光标置于输入值的末尾。
这是没有反应形式的示例。
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();
}
}
Run Code Online (Sandbox Code Playgroud)
似乎也可以开箱即用。然而,无论如何,Angular Reactive Forms 都是一种幸福。
| 归档时间: |
|
| 查看次数: |
10242 次 |
| 最近记录: |