Angular TextArea - Handle the Keyboard Events
The TextArea raises four keyboard events: keyDown, keyPress, keyUp and enterKey. Within the functions that handle them, you can access the original keyboard events. If you are not going to change the functions during the lifetime of the UI component, assign them to the respective UI component properties.
- <dx-text-area
- (onKeyDown)="onKeyDown($event)"
- (onKeyPress)="onKeyPress($event)"
- (onKeyUp)="onKeyUp($event)"
- (onEnterKey)="onEnterKey($event)">
- </dx-text-area>
- import { DxTextAreaModule } from "devextreme-angular";
- // ...
- export class AppComponent {
- onKeyDown (e) {
- const keyCode = e.event.key;
- // Event handling commands go here
- }
- onKeyPress (e) {
- const keyCode = e.event.key;
- // Event handling commands go here
- }
- onKeyUp (e) {
- const keyCode = e.event.key;
- // Event handling commands go here
- }
- onEnterKey (e) {
- // Event handling commands go here
- }
- }
- @NgModule({
- imports: [
- // ...
- DxTextAreaModule
- ],
- // ...
- })
If you are going to change the handling functions at runtime, or if you need to attach several functions to a single event, use the on(eventName, eventHandler) method. This approach is more typical of jQuery.
- const keyDownHandler1 = function (e) {
- const keyCode = e.event.key;
- // First handler of the "keyDown" event
- };
- const keyDownHandler2 = function (e) {
- const keyCode = e.event.key;
- // Second handler of the "keyDown" event
- };
- $("#textAreaContainer").dxTextArea("instance")
- .on("keyDown", keyDownHandler1)
- .on("keyDown", keyDownHandler2);
You can implement a custom handler for a key using the registerKeyHandler(key, handler) method.
- import { ..., ViewChild, AfterViewInit } from '@angular/core';
- import { DxTextAreaModule, DxTextAreaComponent } from 'devextreme-angular';
- // ...
- export class AppComponent implements AfterViewInit {
- @ViewChild(DxTextAreaComponent, { static: false }) textArea: DxTextAreaComponent;
- // Prior to Angular 8
- // @ViewChild(DxTextAreaComponent) textArea: DxTextAreaComponent;
- ngAfterViewInit () {
- this.textArea.instance.registerKeyHandler('backspace', function(e) {
- // The argument "e" contains information on the event
- });
- this.textArea.instance.registerKeyHandler('space', function(e) {
- // ...
- });
- }
- }
- @NgModule({
- imports: [
- // ...
- DxTextAreaModule
- ],
- // ...
- })
See Also
If you have technical questions, please create a support ticket in the DevExpress Support Center.