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 輸入框 - 控制子元件的方法或狀態 - 取得動態內容
實作
- 建立含
<input #nameInput>的元件 - 用
@ViewChild在按鈕按下去時 focus - 改用類別型
@ViewChild(ChildComponent)呼叫子元件方法
作業
- 用
#ref+@ViewChild操作 DOM - 在
ngAfterViewInit使用子元件 - 說明
ElementRef.nativeElement代表什麼