添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Sample code improvement - 'keyCode' is deprecated.ts(6385) #43928

Closed
@cgers

Description

@cgers

Please find the page:
https://angular.io/guide/observables#creating-observables

The two following code snippets are provided:

Create with custom fromEvent function

function fromEvent<T extends keyof HTMLElementEventMap>(target: HTMLElement, eventName: T) {
  return new Observable<HTMLElementEventMap[T]>((observer) => {
    const handler = (e: HTMLElementEventMap[T]) => 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);

Now you can use this function to create an observable that publishes keydown events:

Use custom fromEvent function

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 = '';

Steps to fix this warning.
ng generate component userinfo
CREATE src/app/userinfo/userinfo.component.html (23 bytes)
CREATE src/app/userinfo/userinfo.component.spec.ts (640 bytes)
CREATE src/app/userinfo/userinfo.component.ts (283 bytes)
CREATE src/app/userinfo/userinfo.component.css (0 bytes)
UPDATE src/app/app.module.ts (483 bytes)

The slightly modified code works.

userinfo.component.html

<input type="text" id="yourname" placeholder="Type your name here"/>

userinfo.component.ts - with fixes

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-userinfo',
  templateUrl: './userinfo.component.html',
  styleUrls: ['./userinfo.component.css'],
export class UserinfoComponent implements OnInit {
  constructor() {}
  ngOnInit(): void {
    const ESC_KEY = 'Escape';
    const nameInput = document.getElementById('name') as HTMLInputElement;
    const subscription = this.fromEvent(nameInput, 'keydown').subscribe(
      (e: KeyboardEvent) => {
        if (e.code === ESC_KEY) {
          nameInput.value = '';
  fromEvent<T extends keyof HTMLElementEventMap>(
    target: HTMLElement,
    eventName: T
    return new Observable<HTMLElementEventMap[T]>((observer) => {
      const handler = (e: HTMLElementEventMap[T]) => 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);

Thank you!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions