@ViewChild, ElementRef를 사용한 Angular의 DOM 조작

@ViewChild



DOM 추상화를 탐색하기 전에 컴포넌트/지시문 클래스 내에서 이러한 추상화에 액세스하는 방법을 이해합시다. Angular는 DOM 쿼리라는 메커니즘을 제공합니다. @ViewChild 및 @ViewChildren 데코레이터의 형태로 제공됩니다. 그것들은 동일하게 작동하지만 전자는 하나의 참조를 반환하고 후자는 여러 참조를 QueryList 객체로 반환합니다. 이 기사의 예제에서는 주로 ViewChild 데코레이터를 사용하고 그 앞에 @ 기호를 사용하지 않을 것입니다.

ViewChild 데코레이터의 기본 구문은 다음과 같습니다.

@ViewChild('child1', {static: false}) firstChild: ElementRef;


요소참조



이것은 가장 기본적인 추상화입니다. 클래스 구조를 관찰하면 연결된 기본 요소만 보유하고 있음을 알 수 있습니다. 여기에서 볼 수 있듯이 네이티브 DOM 요소에 액세스하는 데 유용합니다.

console.log(this.tref.nativeElement.innerHTML);

// it will same as the vanilla javascript document.getElementById('child1')


@viewChild 및 ElementRef를 사용해 보겠습니다.

<div #child1>First Child</div>
<div #child2>Second Child</div>

<div #errors>2 Errors</div>



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

@Component({
  selector: 'app-dom-manipulation',
  templateUrl: './dom-manipulation.component.html',
  styleUrls: ['./dom-manipulation.component.scss']
})
export class DomManipulationComponent implements OnInit, AfterViewInit {

  message: any;

  @ViewChild('child1', {static: false}) firstChild: ElementRef;
  @ViewChild('child2', {static: false}) secondChild: ElementRef;
  @ViewChild('errors', {static: false}) errorChild: ElementRef;

  constructor() { }

  ngOnInit() {
    this.message = 'Awais Text Change.';
  }

  ngAfterViewInit() {
    // firstChild
    console.log("before change > ", this.firstChild.nativeElement.innerText);
    this.firstChild.nativeElement.innerText = this.message;
    console.log("after change > ", this.firstChild.nativeElement.innerText);

    // secondChild
    this.secondChild.nativeElement.style.background = 'red';
    this.secondChild.nativeElement.style.color = 'white';

    // error
    let splitted = this.errorChild.nativeElement.innerText.split(" ");
    console.log("splitted >", splitted);

    // constructing new DOM after splitting
    this.errorChild.nativeElement.innerHTML = `
      <div class="errors-head">
        <span class="number">${splitted[0]}</span>
        <span class="typo">${splitted[1]}</span>
      </div>
    `;
  }

}



그게 다야 :)

좋은 웹페이지 즐겨찾기