Issue
I cannot define specific type when using FromEvents
from 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">
Solution
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.
Answered By - Emmanuel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.