angular - 将 null 设置为输入字段的空字符串值

标签 angular angular2-template

我有一个 input 字段映射到我的 Controller 中的一个实体,带有 ngModel 双向绑定(bind):

<input type="text" [(ngModel)]="entity.one_attribute" />

当我初始化我的 Controller 时,我有这个实体:

{ one_attribute: null }

如果用户开始填写字段但没有立即提交表单并清空该字段,我的实体将更新为:

{ one_attribute: "" }

是否可以定义将空字符串自动更改为null

最佳答案

在查看了一堆关于 ValueAccessorHostListener 解决方案的答案后,我制定了一个可行的解决方案(使用 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/

相关文章:

angular - 测试订阅服务

angular - 当 RowData 更改时,Angular 中的 Ag-grid 不会刷新

javascript - anchor 标记不起作用

大型项目列表的 Angular 2 性能优化

angular - 使用模板时如何防止 PrimeNG Tree onNodeSelect() 触发?

javascript - Angular 2 Html 选择模型与选项值不匹配

angular - 获取 Angular 2 中的 mdslider 值?

Angular2 + RxJS BehaviorSubject 订阅不适用于所有组件

angular - 如何在 ngFor 中引用控件?

angular - 如何使用angularfire2检查 child 是否存在于firebase列表中