将null设置为输入字段的空字符串值 [英] Set null as empty string value for input field
问题描述
我有一个input
字段映射到控制器中具有ngModel
2向绑定的实体:
I have an input
field mapped to an entity in my controller with a ngModel
2-way binding:
<input type="text" [(ngModel)]="entity.one_attribute" />
初始化控制器时,我拥有以下实体:
When I initialize my controller, I have this entity:
{ one_attribute: null }
如果用户开始填写该字段,但没有立即提交表单并清空该字段,则我的实体将更新为:
If a user starts to fill in the field but does not submit the form immediately and empties the field, my entity is updated to become:
{ one_attribute: "" }
是否可以定义将空字符串自动更改为null
?
Is it possible to define that empty string should be changed to null
automatically?
推荐答案
查看了关于ValueAccessor
和HostListener
解决方案的一堆答案之后,我制定了一个可行的解决方案(已通过RC1测试):
After viewing a bunch of answers about ValueAccessor
and HostListener
solutions, I made a working solution (tested with RC1):
import {NgControl} from "@angular/common";
import {Directive, ElementRef, HostListener} from "@angular/core";
@Directive({
selector: 'input[nullValue]'
})
export class NullDefaultValueDirective {
constructor(private el: ElementRef, private control: NgControl) {}
@HostListener('input', ['$event.target'])
onEvent(target: HTMLInputElement){
this.control.viewToModelUpdate((target.value === '') ? null : target.value);
}
}
然后以这种方式在您的输入字段中使用它:
Then use it that way on your input fields:
<input [(ngModel)]="bindedValue" nullValue/>
这篇关于将null设置为输入字段的空字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!