为什么以反应形式将空字符串设置为null成为空字符串 [英] Why set empty string as null in reactive form become empty string

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

问题描述

我正在尝试将每个输入的字符串转换为空。
因此,我创建了一个指令来侦听每个更改,并将null分配给空字符串。

I'm trying to convert every string input to null upon cahnge. So i create a directive to listen on every change and assign null to empty string.

这是HTML

<form [formGroup]="form" class="mt-4 p-2" (ngSubmit)="onSubmit()">
  <input nbInput fullWidth fieldSize="small" shape="semi-round" formControlName="AuthorityNum" EmptyToNull>
</form>

这是指令代码:

import { Directive, Input, HostListener, ElementRef } from 
'@angular/core';

@Directive({
selector: '[EmptyToNull]'
})
export class NullValueDirective {

 constructor() {
 }

 @HostListener('change', ['$event.target.value']) onKeyDowns(value) {
 if (value === '') {
  value = null;
  console.log(value) // print: null
  }
 }
}

它似乎将值更改为null

It looks like it change the value to null

但是当我提交表单并检查form.value时,它显示为空字符串

But when i submit the form and inspect the form.value it appears as empty string again.

为什么?

更新

这是我的提交功能:

onSubmit() {
 // TODO: Send to server
  this.form.value.AuthorityNum === '' // true
  }

这是stackblitz上的代码: https://stackblitz.com/edit/angular -ilcg7y

Here is the code at stackblitz: https://stackblitz.com/edit/angular-ilcg7y

推荐答案

您的代码有几个问题:


  1. 指令需要返回值,以便可以绑定到相应的表单控件:

export class NullValueDirectiveDirective {

   @Output('EmptyToNull') response = new EventEmitter<string>();

   @HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) {
      this.response.emit(null);
   }
}


  • 接下来,您需要绑定模板到发射的值:

    <input  formControlName="AuthorityNum" 
    (EmptyToNull) = "form.controls.AuthorityNum.value = $event">
    


  • 这篇关于为什么以反应形式将空字符串设置为null成为空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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