Skip to content

Instantly share code, notes, and snippets.

@karkianish
Last active February 5, 2019 19:24
Show Gist options
  • Save karkianish/c9e38eff1effb98a1dc13139f9693898 to your computer and use it in GitHub Desktop.
Save karkianish/c9e38eff1effb98a1dc13139f9693898 to your computer and use it in GitHub Desktop.
Set Focus to Input Element - Angular 2 +
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
// thanks to the article https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f
/*
key idea is:
identify the element from the dom tree (we accomplish this by giving id to the element and using ViewChild('id') to retrieve the element.
once we have the element as ElementRef (learn more about that), we can call focus() method on it.
*/
@Component({
selector: 'app-my',
template: `
<input #nameInput type='text' formControlName='name' placeholder='name'/>
<button (click)='onClick()'>click me!</button>
`
})
export class AppComponent implements OnInit{
mainForm: FormGroup;
@ViewChild('nameInput') nameInput: ElementRef;
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.mainForm = this.fb.group({
name: ''
});
}
onClick(): void {
this.nameInput.nativeElement.focus();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment