Select the text inside an input using Typescript in Angular 2

Viewed 5026

I'm trying to do exactly what is described in this post, but in Angular2.

Basically use the javascript function .setSelectionRange(start, end); in an input after a user clicks on a trigger. I can't find any way to replicate this behaviour using Typescript.

Thanks in advance.

2 Answers

This example line of code shows the essence of selecting the text (with .name being an ElementRef reference):

this.name.nativeElement.setSelectionRange(0, 999);

Here are all the necessary pieces put together (as well as putting focus on the input) for a "name" field:

View:

<input name="name" formControlName="name" type="text" [(ngModel)]="data.name">

Component:

export class MyComponent {
  @ViewChild('name') name: ElementRef; // * see security comment below for ElementRef
  @Input() data: {name: 'Foo Baz'};
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      name: new FormControl()
    });
  }

  // call this to give the field focus and select its text
  focusAndSelectNameFieldText(){
    if (!this.name) return;
    this.name.nativeElement.focus();
    setTimeout(() => {
      this.name.nativeElement.setSelectionRange(0, 999);
    });
  }
}

*Please be sure your use of ElementRef does not pose a security risk: https://stackoverflow.com/a/44509202/442665

Related