Angular 2+ One way data binding from view target to data source

1.1k views Asked by At

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?

2

There are 2 answers

2
Amit Chigadani On BEST ANSWER

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

1
ConnorsFan On

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.