我有一个 input
字段映射到我的 Controller 中的一个实体,带有 ngModel
双向绑定(bind):
<input type="text" [(ngModel)]="entity.one_attribute" />
当我初始化我的 Controller 时,我有这个实体:
{ one_attribute: null }
如果用户开始填写字段但没有立即提交表单并清空该字段,我的实体将更新为:
{ one_attribute: "" }
是否可以定义将空字符串自动更改为null
?
最佳答案
在查看了一堆关于 ValueAccessor
和 HostListener
解决方案的答案后,我制定了一个可行的解决方案(使用 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);
}
}
然后在您的输入字段中以这种方式使用它:
<input [(ngModel)]="bindedValue" nullValue/>
关于angular - 将 null 设置为输入字段的空字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527535/