1

In my angular application, I have a element that allows a user to set a description value. I want that value to be acceccable in the Data Source. I got this to work using 2-way data binding, as shown below:

<textarea id="MediaDescription" name="description" class="form-control" [(ngModel)]="description"></textarea>

However, given my use case, 2-way data binding is unnecessary here. While the View Model needs to be able to update the Data Source, the opposite is not true.

I tried doing this using (ngModelChange), but this doesn't seem to get called (I tested this by outputting the value via the OnChanges() method in the Data Source).

How can I best re-write this code such that my <textarea> value is only bound from the View Source to the Data Source, not the other way around?

nmg49
  • 1,356
  • 1
  • 11
  • 28

2 Answers2

1

You really dont need ngModel here. Instead you can listen for change event

<textarea id="MediaDescription" name="description" class="form-control" (change)="description = $event.target.value"></textarea>

Note : (change) event is triggered only when text-area element looses the focus. This is the limitation.

DEMO

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
  • Thank you, this worked! Out of curiosity though, how come `(change)` is getting fired here but `(ngModelChange)` isn't? – nmg49 Aug 15 '18 at 14:00
  • 3
    Simple, because you don't have `ngModel` registered. `(ngModelChange)` wont work without `ngModel` – Amit Chigadani Aug 15 '18 at 14:01
1

To update the data source every time the textarea content changes, without using data binding, you can apply the ngModel directive by itself to allow (ngModelChange) to be triggered:

<textarea name="description" ngModel (ngModelChange)="description = $event" ...></textarea>

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146