•  


Event binding ? Angular
In-depth Guides
Template Syntax

Event binding

Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.

Binding to events

HELPFUL: For information on binding to properties, see Property binding .

To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right.

Create the following example; the target event name is click and the template statement is onSave() .

Event binding syntax

      
< button ( click )= "onSave()" > Save </ button >

The event binding listens for the button's click events and calls the component's onSave() method whenever a click occurs.

Syntax diagram

Determining an event target

To determine an event target, Angular checks if the name of the target event matches an event property of a known directive.

Create the following example: (Angular checks to see if myClick is an event on the custom ClickDirective )

src/app/app.component.html

      
< h1 id = "event-binding" > Event Binding </ h1 >
< div class = "group" >
< h3 > Target event </ h3 >
< button type = "button" ( click )= "onSave($event)" > Save </ button >
< button type = "button" on-enter = "onSave()" > on-click Save </ button >
< h4 > myClick is an event on the custom ClickDirective: </ h4 >
< button type = "button" ( myClick )= "clickMessage=$event" clickable > click with myClick </ button >
{{ clickMessage }}
</ div >
< div class = "group" >
< h3 > $event and event handling statements </ h3 >
< h4 > Result: {{ currentItem.name }} </ h4 >
< input [ value ]= "currentItem.name"
( input )= "currentItem.name=getValue($event)" >
without NgModel
</ div >
< div class = "group" >
< h3 > Binding to a nested component </ h3 >
< h4 > Custom events with EventEmitter </ h4 >
< app-item-detail ( deleteRequest )= "deleteItem($event)" [ item ]= "currentItem" > </ app-item-detail >
< h4 > Click to see event target class: </ h4 >
< div class = "parent-div" ( click )= "onClickMe($event)" clickable > Click me (parent)
< div class = "child-div" > Click me too! (child) </ div >
</ div >
< h3 > Saves only once: </ h3 >
< div ( click )= "onSave()" clickable >
< button type = "button" ( click )= "onSave($event)" > Save, no propagation </ button >
</ div >
< h3 > Saves twice: </ h3 >
< div ( click )= "onSave()" clickable >
< button type = "button" ( click )= "onSave()" > Save with propagation </ button >
</ div >

If the target event name, myClick fails to match an output property of ClickDirective , Angular will instead bind to the myClick event on the underlying DOM element.

Binding to keyboard events

You can bind to keyboard events using Angular's binding syntax. You can specify the key or code that you would like to bind to keyboard events. The key and code fields are a native part of the browser keyboard event object. By default, event binding assumes you want to use the key field on the keyboard event. You can also use the code field.

Combinations of keys can be separated by a . (period). For example, keydown.enter will allow you to bind events to the enter key. You can also use modifier keys, such as shift , alt , control , and the command keys from Mac. The following example shows how to bind a keyboard event to keydown.shift.t .

<input (keydown.shift.t)="onKeydown($event)" />

Depending on the operating system, some key combinations might create special characters instead of the key combination that you expect. MacOS, for example, creates special characters when you use the option and shift keys together. If you bind to keydown.shift.alt.t , on macOS, that combination produces a ˇ character instead of a t , which doesn't match the binding and won't trigger your event handler. To bind to keydown.shift.alt.t on macOS, use the code keyboard event field to get the correct behavior, such as keydown.code.shiftleft.altleft.keyt shown in this example.

<input (keydown.code.shiftleft.altleft.keyt)="onKeydown($event)" />

The code field is more specific than the key field. The key field always reports shift , whereas the code field will specify leftshift or rightshift . When using the code field, you might need to add separate bindings to catch all the behaviors you want. Using the code field avoids the need to handle OS specific behaviors such as the shift + option behavior on macOS.

For more information, visit the full reference for key and code to help build out your event strings.

Binding to passive events

Angular also supports passive event listeners.

This is an advanced technique that is not necessary for most applications. You may find this useful if you need to optimize handling of frequently occurring events that are causing performance problems.

For example, use the following steps to make a scroll event passive.

  1. Create a file zone-flags.ts under src directory.

  2. Add the following line into this file.

          
    ( window as any )[ '__zone_symbol__PASSIVE_EVENTS' ] = [ 'scroll' ];
  3. In the src/polyfills.ts file, before importing zone.js, import the newly created zone-flags .

          
    import './zone-flags' ;
    import 'zone.js' ; // Included with Angular CLI.

After those steps, if you add event listeners for the scroll event, the listeners will be passive .

What's next

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본