Template Reference Variables

基本概念

除了 [(ngModel)],Angular 提供了另一種方式存取表單元素的值:Template Reference Variables(模板參考變數)。

這種方式使用 # 符號定義變數:

<input name="title" id="title" #titleInput />

使用範例

一旦定義了 template variable,就可以在整個模板中使用它(不需要加 #):

<form (ngSubmit)="onSubmit(titleInput)">
  <app-control label="Title">
    <input name="title" id="title" #titleInput />
  </app-control>
  
  <app-control label="Request">
    <textarea name="request" id="request" rows="3"></textarea>
  </app-control>
  
  <p>
    <button appButton>
      Submit
      <span ngProjectAs="icon">⌲</span>
    </button>
  </p>
</form>

在元件中使用

在元件中接收這個參數時,需要指定正確的型別:在這邊是 HTMLInputElement,不同標籤會不一樣。

onSubmit(titleElement: HTMLInputElement) {
  console.dir(titleElement);
}

印出來之後會看到這樣的東西

其中,我們可以透過 value 取得 input 的值

所以就可以這樣用

  onSubmit(titleElement: HTMLInputElement) {
    console.log(titleElement.value);
  }

Last updated