Vyhledávání na webu

typescript - umístit kurzor na konec hodnoty vstupního pole při získání fokus | angular 2


Mám vytvářenou dynamickou komponentu a v ngAfterViewInit jsem udělal následující kód:

setTimeout(() => {
  this.input.nativeElement.focus();
}, 0);

Toto funguje: správně nastaví fokus na vstup, ale kurzor je umístěn na začátek hodnoty. Chtěl bych kurzor umístit na konec hodnoty.

Zkoušel jsem toto:

setTimeout(() => {
  this.input.nativeElement.focus();
  let start = this.input.nativeElement.selectionStart;
  let end = this.input.nativeElement.selectionEnd;
  this.input.nativeElement.setSelectionRange(start,end);
}, 0);

Také jsem zkoušel vymazat hodnotu a resetovat ji, ale nemohu to rozchodit.

Tady je HTML a jak k němu přistupuji:

<input class="nav-editor__input" #input type="text">

@ViewChild('input') input: ElementRef;

Máte nějaké nápady?

Odpověď č. 1

Při použití reaktivních formulářů Angular to vypadá, že funguje hned po vybalení. Zde je příklad.

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();
  }
}

Nastavení fokusu v ngAfterViewInit() přesune kurzor na konec hodnoty vstupu.

Zde je příklad bez reaktivních formulářů.

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();
  }
}

Zdá se také, že funguje hned po vybalení. Nicméně Angular Reactive Forms je stejně požehnáním.

Související články