Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Unexpected behavior) Conditional two-way binding in Angular template [(ngModel)]

Tags:

angular

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

like image 337
hnb Avatar asked Jul 17 '26 20:07

hnb


1 Answers

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

like image 77
Mayur Kukadiya Avatar answered Jul 26 '26 03:07

Mayur Kukadiya