Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
How to avoid using 'any' when using FromEvent RxJS with Angular to subscribe to input tag value changes?

I cannot define specific type when using FromEventsfrom RxJS. When I pipe the 'keyup' event and map it to get the inputed value, I can only use (e: any => return (e.target!).value;). Even though the browser's debuggers identifies the e as a KeyboardEvent, if I define e: KeyboardEvent I get an error stating that "e does not contain property target". The current code works, however, since I am new to RxJS + Angular, and the community always advise to avoid using any, so I wonder what can I do to avoid using it in this situation ?

Component.ts

import { TagInterface } from './../../../interfaces/tag/tag-interface';
import { Component, OnInit, Output, EventEmitter, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
import { fromEvent, Observable } from 'rxjs';


@Component({
  selector: 'app-tag-search-bar',
  templateUrl: './tag-search-bar.component.html',
  styleUrls: ['./tag-search-bar.component.scss']
})
export class TagSearchBarComponent implements OnInit,AfterViewInit {

  @Output() tags = new EventEmitter<TagInterface[]>();
  @ViewChild('tagInput') tagInputChild!: ElementRef;

  mappedAndFilteredInput!: Observable<any>;
  eventKeyUp! : Observable<any>;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit() {
    this.eventKeyUp = fromEvent(this.tagInputChild.nativeElement, 'keyup');
    this.mappedAndFilteredInput = this.eventKeyUp.pipe(
      map((e: any) => {
        return (e.target!).value;
      }),
      debounceTime(100),
      distinctUntilChanged(),
      filter(value => (value != "" && value != undefined)) 
    );

    this.mappedAndFilteredInput.subscribe(
      value => console.log(value),
      error => console.log(`error: ${error}`),
      () => console.log('completed maping and filtering tag input term'));
  }
}

HTML

<div class="input-group-prepend">
    <span class="input-group-text">
        <i class="far fa-filter"></i>
    </span>
</div>
<input #tagInput type="text" class="filter-tag-list">
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's the type-safe way to get the target from a KeyboardEvent

    fromEvent<KeyboardEvent>(document.documentElement, 'keyup').subscribe(e => {
      const [target] = e.composedPath()
      console.log(target)      
    })

However, in your case it would be simpler to just do

fromEvent(this.tagInputChild.nativeElement, 'keyup').subscribe(_ => {
  console.log(this.tagInputChild.nativeElement.value)
})

Or better still use a form control, and listen to valueChanges on the form control.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda