问题描述
我有一个要求,只有在电话号码存在的情况下,我才需要将其绑定到ngModel.我的代码如下:
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:
因此,根据此SO帖子 LINK ,我尝试了以下操作:
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.
解决此问题的一种方法是使用*ngIf
并再次重复代码集.但是,我应该做些什么来做内联处理,例如三元条件检查?
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?
推荐答案
我会这样做:
[ngModel]="phone_numbers && phone_numbers[0]?.full_number"
(ngModelChange)="phone_numbers?.length && phone_numbers[0].full_number=$event"
为什么?
[(ngModel)]
扩展为[ngModel]
(输入)和(ngModelChange)
(输出).
[(ngModel)]
is expanded to [ngModel]
(Input) and (ngModelChange)
(Output).
我通过了
phone_numbers && phone_numbers[0]?.full_number
以确保我们在组件类中具有phone_numbers
属性,并且至少具有一项.而且我在这里也使用安全的导航操作符
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
当我们在输入ngModelChange
处理程序中键入内容时,我将在此处执行相同的操作以检查undefined
值,除非我不能在分配中使用安全的导航管道((ngModelChange)="phone_numbers && phone_numbers[0]?.full_number=$event"
将不起作用)
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)
如果您使用webstorm并看到Must be lValue
错误,则请参见以下答案:
If you use webstorm and see Must be lValue
error then see this answer:
这篇关于Angular2中的条件ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!