Ternary Operator in Angular two-way binding
Once upon a time, I want to do a conditional two-way binding in Angular, I wrote code like this:
<input type="text" [(ngModel)]="condition ? values['fullName'] : values['name']">
I want to bind to different fields in values object according to the condition. However, it only works when the condition is false.
If I change the code to this:
<input type="text" [(ngModel)]="values[condition ? 'fullName' : 'name']">
And it works no matter the result of the condition.
Here’s the full example of this:
After digging into the source code, the root cause happened in the template parsing.
Angular will convert [(ngModel)]
to [ngModel]
and (ngModelChange)
this._bindingParser.parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
The problem is it just append the =$event
after the expression, which causes condition ? values['fullName'] : values['name']
converts to condition ? values[‘fullName’] : values[‘name’]=$event
. Therefore, the value assignment only happens when the condition is false.