結論
- ElementRef は、Angularで ディレクティブやコンポーネントが、対応するHTML要素を参照するためのオブジェクト
- オリジナルディレクティブ作る際などに使用
詳細
ElementRefがないと何が困る?
例えば、HTMLに次の入力欄があるとする
<input type="text" focus>
- この入力欄に自動でフォーカスを当てたい
- でも、TSファイルに書いたオリジナルディレクティブから、どうやってこのHTMLの入力欄を操作すればいいのか
→そこで登場するのが ElementRef
ElementRef使用例
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[focus]',
standalone: true
})
export class FocusDirective implements AfterViewInit {
constructor(private el: ElementRef<HTMLInputElement>) {}
ngAfterViewInit() {
//実際のinput要素が持つ focus() メソッドを呼び出す
this.el.nativeElement.focus();
}
}
- ElementRef は、HTML要素への参照を提供するオブジェクト
→今回は<HTMLInputElement>としているのでHTMLの 要素への参照を提供する - el.nativeElementを通じてブラウザー上にある実際のinput要素にアクセスできる
- 概念的には、次のような関係
el // ElementRefオブジェクト
el.nativeElement // 実際のHTML要素
el.nativeElement.focus() // HTML要素のメソッドを実行