How does angular get to use DOM elements in a component?
how does angular get to use DOM elements in a component?
angular rookie, using angular to develop product component, wants to use RXJS"s debounceTime delay for input in this component to implement user input end delay 400ms update.
fromEvent(inputNode, "valueChanges").pipe(
debounceTime(400)
)
.subscribe((val) => {
console.log(val);
// this.keyword = val;
});
.html
.ts
tell me how to get the corresponding DOM element and use it. Do you want to use the event method event.target?
you can try @ ViewChild ()
<textarea -sharpcommentTextarea id="comment" [(ngModel)]="comment" name="comment" placeholder="..." (keyup)="autoSize()"></textarea>
epxort class YourComponent {
@ViewChild('commentTextarea') commetTextarea: ElementRef
...
autoSize() {
this.commetTextarea.nativeElement.style.height = this.commetTextarea.nativeElement.scrollHeight + 'px'
}
}
it's possible to use ElementRef
first, but there are some problems with the code.
- cannot get the DOM element in
constructor ()
, so the typed result is null
.
-
The event parameter of the
fromEvent
method is incorrect. This should be an event of DOM itself. You can try using the input
event.
here is an example of my success:
// Angular6 + rxjs6
ngOnInit(): void {
console.log('oninit: ', this.elRef.nativeElement.querySelector('-sharpsearcha'));
const searchInput = this.elRef.nativeElement.querySelector('-sharpsearcha');
this.inputSubscription = fromEvent(searchInput, 'input')
.pipe(debounceTime(1000))
.pipe(map((val: any) => val.target.value))
.subscribe(val => {
console.log(val);
});
}
ngOnDestroy(): void {
this.inputSubscription.unsubscribe();
}
For more discussion, please refer to
https://stackoverflow.com/que..
in fact, this method is no longer recommended by Angular. Refer to the documentation https://angular.io/api/core/E.
.
does not seem to work, prompting this.commetTextarea undefined
I don't know if you have solved it. I recommend a method that has been used in a project. You don't need to directly manipulate the dom element, use Subject to pass the input value, and then use the rxjs operator to complete the specific operation.
<input type="text" -sharpsearchInput (keyup)="search.next(searchInput.value)">
search: Subject<string> = new Subject<string>();
ngOnInit() {
this.search.asObservable().debounceTime(400).filter().map().subscribe();
}