sexta-feira, 22 de setembro de 2017

Focus and move cursor in Angular

HTML5 brings the autofocus attribute to the input tag.
This attribute works fine when the page is loaded the first time, but in some moments is necessary put the focus in runtime, e.g. after a validation.

In AngularJS I use the code below (unfortunately I did not save the link from where I copied it to thank):

function cursorToEnd(input) {

    // If this function exists...
    if (input.setSelectionRange) {
        // ... then use it (Doesn't work in IE)
        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(input).val().length * 2;

        input.setSelectionRange(len, len);
    } else {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    input.scrollTop = 999999;        

function focus(jQueryObject) {
    setTimeout(function() {
    }, 500);

In my apps using Angular 4 I rewrite it to:

  cursorToEnd(input: ElementRef) {

    if (input.nativeElement.setSelectionRange) {
      const len = input.nativeElement.value.length * 2;
      input.nativeElement.setSelectionRange(len, len);

    input.nativeElement.scrollTop = 999999;

  focus(input: ElementRef) {
      setTimeout(() => this.cursorToEnd(input), 300);

Nenhum comentário:

Postar um comentário