18
votes

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?

3

3 Answers

18
votes

You can split up- and downwards-binding like

<input [ngModel]="x?.y?.z" (ngModelChange)="x?.y?.z ? x.y.z = $event : null"> 
1
votes
<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

1
votes

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)