Po Béo Po Béo - 4 months ago 561
Javascript Question

Angular 2 onload event for a navtive DOM element

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. Any ideas on this? Any other solutions are appreciated. Thanks.

PS: I tried
autofocus
once but it seems not working.

Answer

You should be able to do it in ngOnInit hook:

import { ViewChild, ElementRef, OnInit } from '@angular/core'

// ...

export class Component implements OnInit {

  @ViewChild('textarea') textarea: ElementRef

  ngOnInit() {
    this.textarea.nativeElement.focus()
  }
}

Where in template you need to set template variable:

<textarea #textarea rows="8" col="60"></textarea>