how to focus on an input in Angular
This is how I solved it:
Template:
<input class="form-control" #swiper formControlName="swipe" placeholder="Swipe">
Component:
import { Component, ElementRef, ViewChild } from '@angular/core';
export class MyClass {
@ViewChild('swiper') swiper: ElementRef;
constructor() {}
onClick() {
this.swiper.nativeElement.focus();
}
}
The key being two things: first using the ViewChild not ViewChildren (thanks @Teddy Stern for that one) and second there is no need to use the Renderer at all, just directly use the nativeElement's focus function.
You are using ViewChildren
which returns a QueryList
You need to use ViewChild
and your code should work.
export class MyClass {
@ViewChild('swiper') swiper: ElementRef;
constructor(private renderer: Renderer) {}
onClick() {
this.swiper.nativeElement.focus();
}
}
if you have a input and a button
<input #myinput>
<button (click)="myinput.focus()">click</button>
If anyone is interested, to focus on an element which is generated dynamically, #name
is not possible to keep in the field as attribute. I found a work around using native JS.
<textarea [(ngModel)]="update.newComment"
[name]="'update-' + index"
placeholder="comment"></textarea>
Now, a trigger to focus on above textarea
could be like
<span (click)="focusOn(index);">Comment</span>
Click event will be handled in ts as
focusOn(fieldName) {
const commmentBoxes = document.querySelectorAll(`textarea[ng-reflect-name="update-${fieldName}"]`);
for( let i in commmentBoxes) {
const element: any = commmentBoxes[i];
const attributs = element.attributes;
for(let j in attributs) {
const attribute = attributs[j];
if (attribute.nodeName === 'ng-reflect-name' && attribute.nodeValue === `update-${fieldName}`) {
element.focus();
}
}
}
}