Search code examples
angularangular2-databinding

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


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?


Solution

  • 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