place cursor at end of value of input field on focus | angular 2

Viewed 6666

I have a dynamic component being created and on ngAfterViewInit I've done the following code:

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

This works: it sets the focus on the input correctly, but the cursor is placed at the beginning of the value. I would like to place the cursor at the end of the value.

I've tried this:

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

I've also tried clearing the value and resetting it but cant get it to work.

Heres the html and how I'm accessing it:

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

@ViewChild('input') input: ElementRef;

Any ideas?

1 Answers

When using Angular Reactive Forms, it seams working out-of-the-box. Here is 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();
  }
}

Setting focus in ngAfterViewInit(), puts cursor to the end of input value.

Here is example without Reactive Forms.

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

Also seems to be working out-of-the-box. However, Angular Reactive Forms is a bliss anyway.

Related