18

What is the best way to use two-way-binding (syntax-sugar) in Angular 2 with the safe navigation operator. I've tried the following.

<input [(ngModel)]="x?.y?.z"> 

But this is not supported.

Is there a way to use sth. like this?

devDan
  • 5,969
  • 3
  • 21
  • 40
Manfred Steyer
  • 479
  • 3
  • 12

3 Answers3

18

You can split up- and downwards-binding like

<input [ngModel]="x?.y?.z" (ngModelChange)="x?.y?.z ? x.y.z = $event : null"> 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Just curious here, but doesn't the elvis operator essentially deprecate the "bananna-in-a-box" binding, since you're forced to split the bindings? – rivanov Oct 17 '18 at 18:05
  • @rivanov not sure what you mean by that, but it needs to be split because you can't assign a value to and expression that uses the Elvis operator (`x?.y?.z = 'foo'` is invalid). – Günter Zöchbauer Oct 17 '18 at 18:09
  • What I mean, seems to already be a feature request: https://github.com/angular/angular/issues/7697 – rivanov Oct 17 '18 at 18:14
  • I understand that people want that, but if you check the 2nd-last comment, you'll see that it's not clear if this is technically possible. – Günter Zöchbauer Oct 17 '18 at 18:30
1
<input [ngModel]="x?.y?.z" (keyup)="changeMe($event.target.value)"> {{x?.y?.z}}

export class ParentCmp {
  x={y:{z:"a"}}
   changeMe(val)
    {
      console.log(val);
      this.x.y.z=val;
    }
}

http://plnkr.co/edit/ZBeSPqf4HUwLOeWSNfZJ?p=preview

micronyks
  • 54,797
  • 15
  • 112
  • 146
1

Angular doesn't support safe navigation operator in two-way bindings. Instead you can do this way:

<!-- <input [(ngModel)]="x?.y"> -->
<input [(ngModel)]="x && x.y"> 

(tested with Angular 9)

afruzan
  • 1,454
  • 19
  • 20