I
I
Ingvar Von Bjork2021-12-19 20:24:04
Angular
Ingvar Von Bjork, 2021-12-19 20:24:04

How to call a function after changing ngModel?

I created something like this input: I would like to track the name change through RxJS along with its wonderful Observer. On the Internet, they mostly suggest using (ngChange). Surely there is no way through the Observer?
<input type="text" [(ngModel)]="name">

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2021-12-20
@Xuxicheta

Make a reactive form, and you will have Observable
In general, [(ngModel)] is sugar for And ngChange is from angular.js [ngModel]="name" (ngModelChange)="name = $event"

A
Andrey Sanych, 2021-12-24
@mountpoint

there are at least 2 ways to solve to get our favorite Observable
1 way
Make a reactive form and listen to changes through valueChanges
2 way
HTML TS
<input type="text" [(ngModel)]="name" #myInput>

@ViewChild('myInput') myInput: ElementRef | undefined;

ngAfterViewInit() {
    fromEvent(this.myInput?.nativeElement, 'keyup') // <- тут слушаете событие, которое Вам нравится
      .pipe(
        map((el: any) => el.target.value),
        takeUntil(this.ngUnsubscribe$),
      )
      .subscribe((value: string) => {
        console.log(value);
      });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question