My ultimate goal is to make a textarea element autofocus on creating. I have just thought of a solution to call e.target.focus()
on event onload
. Something like:
<textarea rows="8" col="60" (load)='handleLoad($event)'>
and then:
handleLoad(e){
e.target.focus();
}
The problem is angular does not recognize load
event.
PS: I tried autofocus
once but it seems not working.
You should be able to do it in ngAfterViewInit hook:
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core'
// ...
export class Component implements AfterViewInit {
@ViewChild('textarea') textarea: ElementRef
ngAfterViewInit() {
this.textarea.nativeElement.focus()
}
}
Where in template you need to set template variable:
<textarea #textarea rows="8" col="60"></textarea>
Try the HTML5 autofocus
attribute:
<textarea rows="8" col="60" autofocus>
Always better (and a lot simpler!) to use the native DOM API if possible than to do it in JavaScript :)
EDIT: The above is incorrect. See my comment below.
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