on
Angular에서 template 내에 있는 element를 참조하는 방법
Angular에서 template 내에 있는 element를 참조하는 방법
반응형
이번 글은 Angular에서 template 내에 있는 element를 참조하는 방법인 Template Variable에 대해 소개해보려 합니다.
이 Template Variable을 사용하면
템플릿에 있는 element를 참조할 수 있습니다. 디렉티브를 참조할 수 있습니다. 컴포넌트를 참조할 수 있습니다.
사용 방법은 참조하고자 하는 host element에 ‘#이름’ 을 attribute를 사용하듯이 추가해주면 됩니다.
Hello World!
예시로 AppComponent 내에서 p태그를 참조하여 Console에 출력해보겠습니다.
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild, } from ‘@angular/core’;@Component({ selector: ‘app-root’, template: ‘hello world!’, styleUrls: [‘./app.component.scss’], }) export class AppComponent implements OnInit, AfterViewInit { @ViewChild(‘content’) p: ElementRef; constructor() {} ngOnInit(): void { console.log(this.p); } ngAfterViewInit(): void { console.log(this.p); } }
Template Variable Console 출력 스크린샷
출력된 결과를 보시면 p 요소를 참조하여 출력한 것을 확인할 수 있습니다.
ngOnInit 에서 undefined 가 출력된 이유는 Angular의 Lifecycle에서 view가 초기화되는 시점이 ngAfterViewInit 일 때 이기 때문에 ngOnInit 일 때는 아직 view가 초기화되지 않아 content라는 Template Variable이 존재하지 않으므로 undefined가 출력되는 것입니다.
Template Variable을 활용해 버튼 클릭시 p태그를 참조하여 값을 가져올 수도 있습니다.
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild, } from ‘@angular/core’; @Component({ selector: ‘app-root’, template: `hello world! click `, styleUrls: [‘./app.component.scss’], }) export class AppComponent implements OnInit, AfterViewInit { @ViewChild(‘content’) p: ElementRef; constructor() {} ngOnInit(): void { console.log(this.p); } ngAfterViewInit(): void { console.log(this.p); } onClick(el: Element): void { console.log(el.innerHTML); } }
버튼 클릭시 Template Variable을 인자로 전달
이렇듯 Template Variable을 사용하면 element에 직접 접근하는 것이 가능합니다.
만약 native element가 아닌 커스텀 컴포넌트일 경우엔 해당 컴포넌트 내에 정의되어 있는 property나 method에 접근하는 것이 가능합니다(단, public 일 경우에만 접근이 가능합니다).
아래와 같이 샘플로 ChildCompComponent를 만들고 AppComponent에서 사용해 보겠습니다.
import { Component, OnInit } from ‘@angular/core’; @Component({ selector: ‘app-child-comp’, templateUrl: ‘./child-comp.component.html’, styleUrls: [‘./child-comp.component.scss’], }) export class ChildCompComponent implements OnInit { isChild: boolean = true; constructor() {} ngOnInit(): void {} }
먼저 위와 같이 ChildCompComponent를 만듭니다.
그리고 AppComponent에서 ChildCompComponent를 사용하고 그 안에 있는 isChild 값을 출력해보겠습니다.
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild, } from ‘@angular/core’; import { ChildCompComponent } from ‘./child-comp/child-comp.component’; @Component({ selector: ‘app-root’, template: `hello world! `, styleUrls: [‘./app.component.scss’], }) export class AppComponent implements OnInit, AfterViewInit { @ViewChild(‘content’) p: ElementRef; @ViewChild(‘child’) child: ChildCompComponent; constructor() {} ngOnInit(): void { console.log(this.p); } ngAfterViewInit(): void { console.log(this.p); console.log(‘child-comp isChild: ‘, this.child.isChild); } }
ChildCompComponent를 참조
결과를 보시면 true가 출력된 것을 확인할 수 있습니다.
이 글에선 소개하지 않았지만 같은 방식으로 directive를 참조하여 제어하는 것도 가능합니다.
이처럼 Template Variable을 사용하면 특정 content로 scroll을 해야하는 경우 또는 자식 컴포넌트의 메소드를 호출해야하는 경우 등과 같이 여러 상황에서 유용하게 사용할 수 있습니다.
반응형
from http://clap-yeon.tistory.com/75 by ccl(A) rewrite - 2021-11-29 15:27:12