angular keydown 例子
...
https://angular.cn/guide/observables keydown example
import { Component } from '@angular/core'; import { Observable, fromEvent } from 'rxjs'; @Component({ selector: 'app-cust', template: `<p><button type="button" (click)="runExample()">{{title}}</button><input id="name" placeholder="type here"></p>`, }) export class CustomersComponent { title = 'fromEvent - How to capture an event e.g. a keypress'; runExample() { console.clear(); // const myInput = document.getElementById('example-d'); // const myObserverable = fromEvent(myInput, 'keyup'); // // myObserverable // .subscribe( // value => console.log(value), // err => console.error(err), // () => console.log('Streaming is over') // ); function fromEvent(target, eventName) { return new Observable((observer) => { const handler = (e) => observer.next(e); // Add the event handler to the target target.addEventListener(eventName, handler); return () => { // Detach the event handler from the target target.removeEventListener(eventName, handler); }; }); } const ESC_KEY = 27; const nameInput = document.getElementById('name') as HTMLInputElement; const subscription = fromEvent(nameInput, 'keydown').subscribe((e: KeyboardEvent) => { if (e.keyCode === ESC_KEY) { nameInput.value = ''; } }); } }