填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

事件繫結的工作原理

How event binding works

在事件繫結中,Angular 會為目標事件配置事件處理函式。你還可以將事件繫結用於自訂事件。

In an event binding, Angular configures an event handler for the target event. You can use event binding with your own custom events.

當元件或指令引發事件時,處理程式就會執行範本語句。範本語句會執行一個動作來響應這個事件。

When the component or directive raises the event, the handler executes the template statement. The template statement performs an action in response to the event.

處理事件

Handling events

處理事件的常見方法之一是把事件物件 $event 傳給處理該事件的方法。$event 物件通常包含該方法所需的資訊,例如使用者名稱或圖片 URL。

A common way to handle events is to pass the event object, $event, to the method handling the event. The $event object often contains information the method needs, such as a user's name or an image URL.

目標事件決定了 $event 物件的形態。如果目標事件是來自原生 DOM 元素的,那麼 $event 是一個DOM 事件物件,它具有 targettarget.value 等屬性。

The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.value.

在下面的例子中,程式碼透過繫結到 name 來設定 <input>value 屬性。

In the following example the code sets the <input> value property by binding to the name property.

src/app/app.component.html
      
      <input [value]="currentItem.name"
       (input)="currentItem.name=getValue($event)">
    

在這個例子中,會發生下列操作:

With this example, the following actions occur:

  1. 該程式碼繫結到 <input> 元素的 input 事件,該事件允許程式碼監聽這些更改。

    The code binds to the input event of the <input> element, which allows the code to listen for changes.

  2. 當用戶做出更改時,該元件會引發 input 事件。

    When the user makes changes, the component raises the input event.

  3. 這個繫結會在一個上下文中執行該語句,此上下文中包含 DOM 事件物件 $event

    The binding executes the statement within a context that includes the DOM event object, $event.

  4. Angular 會透過呼叫 getValue($event.target) 來獲取更改後的文字,並用它更新 name 屬性。

    Angular retrieves the changed text by calling getValue($event.target) and updates the name property.

如果該事件屬於某個指令或元件,那麼 $event 就具有指令或元件中產生的形態。

If the event belongs to a directive or component, $event has the shape that the directive or component produces.

在範本中,$event.target 的型別只是 EventTarget。在 getValue() 方法中,把此目標轉為 HTMLInputElement 型別,以允許對其 value 屬性進行型別安全的訪問。

The type of $event.target is only EventTarget in the template. In the getValue() method, the target is cast to an HTMLInputElement to allow type-safe access to its value property.

      
      getValue(event: Event): string {
  return (event.target as HTMLInputElement).value;
}