将 null 设置为输入字段的空字符串值 [英] Set null as empty string value for input field

查看:62
本文介绍了将 null 设置为输入字段的空字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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?

推荐答案

在查看了一堆关于 ValueAccessorHostListener 解决方案的答案后,我做了一个可行的解决方案(经过测试与 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆