I was going through the Angular documentation and saw the following code snippet. In the back of my mind, I thought I recalled that using document.getElementById()
in Angular is frowned upon, and even using ElementRefs
is discouraged (to help prevent XSS attacks). If these are indeed discouraged, what is the best practice to set up an Observable for events on a particular element?
from Angular Observables Documentation
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
const searchBox = document.getElementById('search-box'); // <-- Is this OK?
const typeahead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => e.target.value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);