Week 07 · Day 04 — ViewChild 與 Template Reference

學習目標

  • @ViewChild 取得子元件/DOM 元素
  • 用模板參考變數 #name 標記目標
  • 控制子元件的狀態或呼叫方法

重點

@ViewChild + 模板參考變數

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

@Component({
  selector: 'app-parent',
  template: `
    <input #nameInput>
    <button (click)="focusInput()">Focus</button>
  `
})
export class ParentComponent {
  @ViewChild('nameInput') nameInput!: ElementRef;

  focusInput(): void {
    this.nameInput.nativeElement.focus();  // 對 DOM 元素 focus
  }
}

關鍵點 - #nameInput:在模板標記變數 - @ViewChild('nameInput'):把該元素注入 ElementRef - nameInput.nativeElement:真正的 DOM 節點 - 需在 ngAfterViewInit 之後才可用(視圖已建立)

看子元件

import { ChildComponent } from './child.component';

@ViewChild(ChildComponent) child!: ChildComponent;

ngAfterViewInit(): void {
  this.child.someMethod();
}
- 也可直接以類別取得子元件實例

最常用時機 - 自動 focus 輸入框 - 控制子元件的方法或狀態 - 取得動態內容

實作

  1. 建立含 <input #nameInput> 的元件
  2. @ViewChild 在按鈕按下去時 focus
  3. 改用類別型 @ViewChild(ChildComponent) 呼叫子元件方法

作業

  • #ref + @ViewChild 操作 DOM
  • ngAfterViewInit 使用子元件
  • 說明 ElementRef.nativeElement 代表什麼