Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to focus on next input field with press enter key in angular4

Tags:

angular

how to focus next input field with enter keypress in angular4

  import { Component, OnInit,ElementRef,ViewChild,Directive,Renderer,AfterViewInit} from '@angular/core';

  @Component({
    selector: 'cbody',
    templateUrl: './cbody.component.html',
    styleUrls: ['./cbody.component.css']
  })  
  export class CbodyComponent  implements  OnInit, AfterViewInit  {

    constructor(public renderer: Renderer,private el:ElementRef) {}

    @ViewChild('ft01') infocus: ElementRef;

    ngOnInit(){};

    ngAfterViewInit() {
          this.renderer.invokeElementMethod(
          this.infocus.nativeElement, 'focus');                     
    }

    keytab(event:any){      
          console.log(event.keyCode );  
          console.log(this.dataloops );     
    }

   dataloops=[
    { "name":"csdn" , "url":"www.runoob.com" }, 
    { "name":"google" , "url":"www.google.com" }, 
    { "name":"ifeng" , "url":"www.weibo.com" }
   ];

  }

 <p>
   cbody works!
 </p>


 <div>
 <ul *ngFor="let dataloop of dataloops">
    <li  >{{dataloop.name}}<input type="text" name="intext" [(ngModel)]="dataloop.url" #ft01 (keyup.enter)="keytab($event)"/></li>
 </ul>
 </div>
like image 975
percinor Avatar asked Aug 07 '17 05:08

percinor


2 Answers

you are using the *ngFor in a wrong way, it repeats the element which is placed on.
you need to set the *ngFor on the li element.

<ul>
    <li *ngFor="let dataloop of dataloops">
       {{dataloop.name}}
        <input type="text" name="intext" 
        [(ngModel)]="dataloop.url" #ft01 (keyup.enter)="keytab($event)"/>  
    </li>
 </ul>  

now update the .ts file as following

keytab(event){
    let element = event.srcElement.nextElementSibling; // get the sibling element

    if(element == null)  // check if its null
        return;
    else
        element.focus();   // focus if not null
}

this code should work fine.

like image 117
Raed Khalaf Avatar answered Oct 04 '22 16:10

Raed Khalaf


you have to use the renderer to access next sibling element; using renderer2 : inject renderer2 in the constructor and then:

this.renderer2.parentNode(this.el.nativeElement).focus();
like image 27
sancelot Avatar answered Oct 04 '22 16:10

sancelot