Angular の ElementRef
ElementRef とは何か、Angular での使用方法を紹介します。
Angular で ElementRef を使って DOM 要素を取得する
ElemenRef は、プロパティ nativeElement を含むネイティブ DOM 要素オブジェクトのラッパーです。DOM 要素への参照を保持し、それを使用して DOM を操作できます。コンポーネントクラスから HTML 要素を取得するために ViewChild とともに使用されます。
例を見て、ElementRef を詳細に理解し、アプリケーションでの使用方法を理解しましょう。
まず、app.component.ts ファイルの@ angle / core から ViewChild、ElementRef、Component、および AfterViewInit をインポートする必要があります。
それらをインポートしたら、クラスで ViewChild を使用して ElementRefDiv を作成します。そして、その値を div に渡す ngAfterViewInit 関数を作成します。
したがって、app.component.ts のコードは次のようになります。
# angular
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChild('ElementRefDiv') ElementView: ElementRef;
ngAfterViewInit() {
console.log(this.ElementView);
this.ElementView.nativeElement.innerHTML = 'Hello I am Using ElementRef To Display this!';
}
}
app.component.html にクラス ElementRefDiv のテンプレートを作成する必要があります。
# angular
<div #ElementRefDiv></div>
出力:

したがって、これらの簡単な手順で、ElementRef と ViewChild を使用して任意の DOM 要素を操作できます。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn