Pho Huynh
Pho Huynh

Reputation: 1577

Angular 2 onload event for a native 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.

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

Upvotes: 19

Views: 69096

Answers (3)

Moslem Shahsavan
Moslem Shahsavan

Reputation: 1337

1) Custom *ref directive

Copy ref.directive.ts from project RefFunc then add to NgModule

use *ref directive on element. call call-back function when element is created.

sample:

<p *ref="changeStyle">Sample 1 :)</p>
 changeStyle(el: ElementRef) {
    (el.nativeElement as HTMLElement).style.backgroundColor = 'rgb(242, 119, 119)';
  }

2) Tricky: use *ngIf directive (complex example).

<!-- this template just for example. -->
<div *ngFor="let tab of page.tabs; let index=index">
    <input #tabCheckboxEle
       id="{{ 'checkbox_' + index }}"
       type="checkbox"
    />
    <label *ngIf="{_: onStateCheckbox(tab, tabCheckboxEle)}"
        for="{{ 'checkbox_' + index }}">{{ tab.title }}</label>
</div>

*ngIf directive create truthy object properties then call function property.

I'm use *ngIf on label element for need input reference.

Upvotes: 0

jessepinho
jessepinho

Reputation: 5782

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.

Upvotes: 9

dfsq
dfsq

Reputation: 193291

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>

Upvotes: 27

Related Questions