Conditional ngModel in Angular2

2020-01-31 02:57发布

问题:

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?

回答1:

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


回答2:

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"


标签: angular