0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Angular】ElementRef

0
Posted at

結論

  • 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要素のメソッドを実行
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?