0

I have a component where there is a textarea. I need to capture a value change in the textarea, then send it to server as PUT request(update). I do not want to update the value on text area lost focus, but rather a auto-save function.

I have seen several articles showing auto-save to the entire form. But I need to auto-save only this particular field's text content.

I came up with a code segment as below, but within it I need to capture the textarea (either by id or etc):

this.subs.add(this.INeedToCaptureFieldById
  .pipe(debounceTime(2000), distinctUntilChanged())
  .subscribe(() => {
    this.updateContent();
  })); 

How to capture the textarea in Angular, but couldnt figure a way. how to capture the textarea "INeedToCaptureFieldById"

sm101
  • 562
  • 3
  • 10
  • 28

1 Answers1

2

You can capture that via ngModelChange event like so:

component.html

<textarea [(ngModel)]="valueVariable" (ngModelChange)="changed()"></textarea>

component.ts

valueVariable: string;

changed():any{
  console.log(this.valueVariable);
}
Asaf
  • 1,446
  • 9
  • 17
  • but for this event to trigger, textarea should loose focus right. I mean like we need to enter text and click somewhere else in the page. I need to autosave without lost-focus – sm101 Sep 18 '20 at 11:31
  • See this working [demo](https://stackblitz.com/edit/angular-playground-zwzqp4?file=app%2Fapp.component.ts) Iv'e created – Asaf Sep 18 '20 at 11:34
  • thank you for this. Will it be possible to have a debounceTime (interval to resend) for this, rather than sending immediately ? – sm101 Sep 18 '20 at 14:33
  • Yes you can, you will need to change it a bit, look [here](https://stackoverflow.com/questions/51780025/debouncetime-in-angular6-ngmodelchange) – Asaf Sep 18 '20 at 18:48
  • 1
    I've changed the code - [demo](https://stackblitz.com/edit/angular-playground-zwzqp4?file=app%2Fapp.component.ts) – Asaf Sep 18 '20 at 18:55