2

I have an unexpected behavior when I use two way binding in Angular dynamically, something like [(ngModel)]="condition ? propA : propB".

For more detail, in my app.component.ts:

@Component({ ... })
export class AppComponent {
  props = { a: 'this is a', b: 'this is b' };
  myCondition = 'a';
}

and my template:

<h2>props a: {{ props.a }} (type anything, last input will change)</h2>
<input #a [(ngModel)]="props.a" />
<hr>

<h2>props b: {{ props.b }}</h2>
<input #b [(ngModel)]="props.b" />
<hr>

<h2>last one (type anything, nothing happen)</h2>
<input #c [(ngModel)]="myCondition === 'a' ? props.a : props.b" />

I thought input#c should have updated props.a but nothing happens at all. However, type something into input#a triggers input#c changed :(

My Caption

Could anyone explain what is going on for me? Thanks.

Stackblitz for this: https://stackblitz.com/edit/angular-ivy-emaszv

hnb
  • 107
  • 1
  • 6

1 Answers1

2

You should try this kind of binding by expanding it like this :

[ngModel]="myCondition === 'a' ? props.a : props.b"
(ngModelChange)="myCondition === 'a' ? props.a=$event : props.b=$event"

Here is stackblitz

More info here

Mayur Kukadiya
  • 2,461
  • 1
  • 25
  • 58
  • So my code was equivalent to ``` [ngModel]='myCondition === "a" ? props.a : props.b' (ngModelChange)='myCondition === "a" ? props.a : props.b' ``` Right? – hnb Jul 13 '21 at 13:40
  • Nope, you have to assign $event to props.a or b according to condition in `ngModelChange`. – Mayur Kukadiya Jul 14 '21 at 04:18