0

how do I remove two way binding with [(ngModel)] in angular?

I want a seperate handler for setting the value, and another for changing it. So I can have side-effects

e.g.

 <input [(ngModel)]="selectedEscrowOffering" [ngbTypeahead]="search" [resultFormatter]="escrowFormatter">

in Vue, models were considered syntatic sugar.

Could I seperate out the two way into a directive and onChangeHandler?

 <input [value]="selectedEscrowOffering" (change)="someFunctionName($event)" [ngbTypeahead]="search" [resultFormatter]="escrowFormatter">
Vincent Tang
  • 3,758
  • 6
  • 45
  • 63
  • It should work just fine. For the initial beta of Angular, I used this approach and only bound the value of ngModel (`[ngModel]`) and handled the change/blur event like you have above. There were race conditions when binding the ngModel change event (using `[()]`) and trying to call an event. Which event was invoked first was not consistent. – ps2goat Mar 26 '20 at 19:39
  • The `(change)` event here would be the input's change event, not an update from ngModel. The model would have to be manually updated in your `someFunctionName` event handler. – ps2goat Mar 26 '20 at 19:40
  • You should consider reading [the documentation on binding types](https://angular.io/guide/template-syntax#binding-types-and-targets). – Heretic Monkey Mar 26 '20 at 19:47

2 Answers2

0

It is very similar to vue, you seperate the @Output and the @Input as follows:
<input (ngModelChange)="someFunctionName($event)" [ngModel]="mymodel">

KLTR
  • 1,263
  • 2
  • 14
  • 37
0

Related to the other answer by KLTR, this is how I got it to work:

This two way binding model:

<input [(ngModel)]="selectedEscrowOffering" 

can be broken down into the following:

<input [ngModel]="selectedEscrowOffering" (ngModelChange)="onChangeEscrowDropdown($event)>

On the typescript side, add the function that sets it. I had it on a typeahead, and it looked for an elements in the array of objects to match it

onChangeEscrowDropdown($event){

  if(typeof $event ==="object"){
    this.selectedEscrowOffering = $event
  }
}
Vincent Tang
  • 3,758
  • 6
  • 45
  • 63