Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional ngModel in Angular2

Tags:

angular

I have a requirement, I need to bind phone number to ngModel only if it's present. My code is as follows:

<cd-input
  size="15"
  [(ngModel)]="phone_numbers[0].full_number"
  [reformat]="something"
  [format]="something"
  placeholder="(111) 222-3333">
</cd-input>

This works well if phone number is present, but if it's not I get the following error:

Cannot read property 'full_number' of undefined

So based on this SO post LINK, I tried the following:

<cd-input
  size="15"
  [(ngModel)]="phone_numbers[0].length > 0 ? phone_numbers[0].full_number : null"
  [reformat]="something"
  [format]="something"
  placeholder="(111) 222-3333">
</cd-input>

But, this causes syntax error.

Uncaught Error: Template parse errors

One way to fix this is using *ngIf and repeating the set of code again. But, What should I do to do it inline, like a ternary condition check?

like image 512
Abhi Avatar asked Jul 17 '17 12:07

Abhi


2 Answers

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:

  • Webstorm: What does "Must be lvalue" mean
like image 66
yurzui Avatar answered Nov 17 '22 06:11

yurzui


For such binding expressions you need to split the property and event binding like:

[ngModel]="phone_numbers[0]?.full_number" 
(ngModelChange)="phone_numbers?.length && phone_numbers[0] ? phone_numbers[0].full_number=$event : null"
like image 21
Günter Zöchbauer Avatar answered Nov 17 '22 05:11

Günter Zöchbauer