Is there a way for Angular2 to focus on the input field?

At the end of the method, I will clear some fields, which is quite simple:

this.modelname.fieldname1 = ""; this.modelname.fieldname2 = "";

But then I would like the cursor to appear in field1.

Is there any way angular2 do this, or am I just using old fashioned javascript?

+4
source share
3 answers

You can use the template reference variable in the first input, which will give you the ability to run .focus()on it.

In the template, you can add # fieldName1 to your input tag (i.e. <input type="text" #fieldName1>)

in your controller:

@ViewChild('fieldName1')
fieldName1: any;

Now you can do it this.fieldName1.nativeElement.focus()in the controller or fieldName1.focus()in the template.

+12

dom Angular. Angular Renderer (Angular2) Renderer 2 (Angular4).

Angular 2:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input #inp id="myInput" type="text">
      <button (click)="setFocus()">Set Focus</button>
    </div>
  `,
})
export class App {
  @ViewChild('inp') inp:ElementRef;

  constructor(private renderer: Renderer) {
  }

  setFocus() {
    this.renderer.invokeElementMethod(this.inp.nativeElement, 'focus');
  }
}

Angular4 Renderer Renderer2. invokeElementMethod : https://github.com/angular/angular/issues/13818#issuecomment-297815331

Angular 4 :

 let onElement = this.renderer2.selectRootElement('#myInput');
 onElement.focus();
+17

renderer @ViewChild . , #id, @julia.

Html:

<textarea  #tasknote name="tasknote"> </textarea> 

JS:

export class MyComponent implements AfterViewInit {
      @ViewChild('tasknote') input: ElementRef;
         constructor(private renderer: Renderer2){           
          }

       ngAfterViewInit() {
       //using selectRootElement instead of deprecated invokeElementMethod
       this.renderer.selectRootElement(this.input["nativeElement"]).focus();
      }

    }

renderer docs

0

Source: https://habr.com/ru/post/1675963/


All Articles