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>
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With