Conditional ngModel in Angular2

I would do it like:

[ngModel]="phone_numbers && phone_numbers[0]?.full_number"
(ngModelChange)="phone_numbers?.length && phone_numbers[0].full_number=$event"

Why?

[(ngModel)] is expanded to [ngModel] (Input) and (ngModelChange)(Output).

I passed

phone_numbers && phone_numbers[0]?.full_number

to input to ensure that we have phone_numbers property in our component class and it has at least one item. And i also use here safe navigation operator

When we type something in input ngModelChange handler is called and i do the same things here for checking undefined value unless i can’t use safe navigation pipe in the assignment ((ngModelChange)="phone_numbers && phone_numbers[0]?.full_number=$event" won’t work)


If you use webstorm and see Must be lValue error then see this answer:

Leave a Comment