{{values}}
` })export class KeyUpComponent_v1{values = ''; onKey(event: KeyboardEvent){this.values += (event.target).value + ' | '; }} In the code above, we listen for an event and capture the user's input. Angular stores the event object in the `$event` variable. The component's `onKey()` method is used to extract the user's input from the event object and then append the input value to the `values` property. * * * ## Getting User Input from a Template Reference Variable You can display user data by using a local template variable. A template reference variable is created by prefixing an identifier with a hash symbol (#). The following example demonstrates how to use a local template variable: ## app/loop-back.component.ts file: @Component({selector: 'loop-back', template: `{{box.value}}
` })export class LoopbackComponent{} We define a template reference variable named `box` on the `` element. The `box` variable references the `` element itself, which means we can access the input element's `value` and display it in the `` tag using interpolation. We can use a template reference variable to modify the previous `keyup` example: ## app/keyup.components.ts (v2) file: @Component({selector: 'key-up2', template: `
{{values}}
` })export class KeyUpComponent_v2{values = ''; onKey(value: string){this.values += value + ' | '; }} * * * ## Filtering Key Events (via key.enter) We can get the input box's value only when the user presses the Enter key. The `(keyup)` event handler listens to every keystroke. We could filter keystrokes, for example, by checking `$event.keyCode` and only update the `values` property when the Enter key is pressed. Angular can filter keyboard events for us by binding to Angular's `keyup.enter` pseudo-event to listen for the Enter key event. ## app/keyup.components.ts (v3): @Component({selector: 'key-up3', template: `{{values}}
` })export class KeyUpComponent_v3{values = ''; } * * * ## The blur (Loss of Focus) Event Next, we can use the `blur` (loss of focus) event, which updates the `values` property after the element loses focus. The following example listens for both the Enter key press and the input box losing focus. ## app/keyup.components.ts (v4): @Component({selector: 'key-up4', template: `{{values}}
` })export class KeyUpComponent_v4{values = ''; } The source code used in this article can be downloaded in the following way, excluding the `node_modules` and `typings` directories. (#)
YouTip