16

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?

Abhi
  • 4,123
  • 6
  • 45
  • 77

2 Answers2

42

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:

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • 1
    This actually worked for me, but can you please add some explanation for me to understand? – Abhi Jul 17 '17 at 12:42
10

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"
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Is it `"phone_numbers?.length && phone_numbers[0] ? phone_numbers[0].full_number=$event : null"` ???. I'm getting error like : Parser Error: Conditional expression phone_numbers[0]?.length ? phone_numbers[0].full_number=$event requires all 3 expressions at the end of the expression – Abhi Jul 17 '17 at 12:31
  • I forgot the last piece at the end - fixed – Günter Zöchbauer Jul 17 '17 at 12:36
  • If this doesn't work, try adding parens `(phone_numbers?.length && phone_numbers[0]) ? ...` – Günter Zöchbauer Jul 17 '17 at 12:37