본문 바로가기

개발 공부/Angular

@ViewChild와 @ViewChildren (2) 기본 활용

템플릿 요소 참조하기

Angular에서는 @ViewChild를 이용하여 특정 템플릿 요소를 직접 조작할 수 있습니다.

1. 버튼을 클릭하면 입력 필드에 자동으로 포커스 주기

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

@Component({
  selector: 'app-input-focus',
  template: `
    <input #inputField type="text" placeholder="이곳을 클릭해 보세요" />
    <button (click)="focusInput()">포커스 주기</button>
  `,
})
export class InputFocusComponent {
  @ViewChild('inputField') inputElement!: ElementRef;

  focusInput() {
    this.inputElement.nativeElement.focus();
  }
}
  • @ViewChild('inputField')를 사용하여 <input> 요소를 참조합니다.
  • focusInput() 메서드에서 nativeElement.focus()를 호출하여 해당 입력 필드에 포커스를 줍니다.
 

자식 컴포넌트의 메서드 호출하기

부모 컴포넌트에서 @ViewChild를 사용하여 자식 컴포넌트의 메서드를 호출할 수도 있습니다.

1. 자식 컴포넌트 정의

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<p>자식 컴포넌트입니다.</p>`
})
export class ChildComponent {
  sayHello() {
    console.log('안녕하세요! 저는 자식 컴포넌트입니다.');
  }
}

2. 부모 컴포넌트에서 자식 컴포넌트의 메서드 호출하기

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: `
    <app-child></app-child>
    <button (click)="callChildMethod()">자식 메서드 호출</button>
  `,
})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent!: ChildComponent;

  ngAfterViewInit() {
    this.childComponent.sayHello();
  }

  callChildMethod() {
    this.childComponent.sayHello();
  }
}
  • @ViewChild(ChildComponent)을 사용하여 ChildComponent의 인스턴스를 참조합니다.
  • callChildMethod()를 통해 자식 컴포넌트의 sayHello() 메서드를 호출할 수 있습니다.
 

QueryList와 @ViewChildren 활용하기

1. 여러 개의 요소 참조하기

@ViewChildren을 사용하면 동일한 CSS 선택자를 가진 여러 요소를 한 번에 가져와 반복적으로 조작할 수 있습니다.

import { Component, QueryList, ViewChildren, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-multiple-elements',
  template: `
    <p #paragraph>첫 번째 문장</p>
    <p #paragraph>두 번째 문장</p>
    <p #paragraph>세 번째 문장</p>
    <button (click)="changeTexts()">문장 변경</button>
  `,
})
export class MultipleElementsComponent implements AfterViewInit {
  @ViewChildren('paragraph') paragraphs!: QueryList<ElementRef>;

  ngAfterViewInit() {
    this.paragraphs.forEach((p, index) => {
      console.log(`Paragraph ${index + 1}:`, p.nativeElement.textContent);
    });
  }

  changeTexts() {
    this.paragraphs.forEach((p, index) => {
      p.nativeElement.textContent = `변경된 문장 ${index + 1}`;
    });
  }
}
  • @ViewChildren('paragraph')를 사용하여 모든 <p> 요소를 QueryList로 가져옵니다.
  • forEach()를 활용하여 모든 요소의 내용을 변경할 수 있습니다.