为什么将空字符串设置为空反应形式成为空字符串

use*_*496 5 events directive typescript angular

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

这是 HTML

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

这是指令代码:

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
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

看起来它会将值更改为 null

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

为什么?

更新

这是我的提交功能:

onSubmit() {
 // TODO: Send to server
  this.form.value.AuthorityNum === '' // true
  }
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*s K 3

您的代码有几个问题:

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

    export class NullValueDirectiveDirective {
    
       @Output('EmptyToNull') response = new EventEmitter<string>();
    
       @HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) {
          this.response.emit(null);
       }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 接下来,您需要在模板上绑定到发出的值:

    <input  formControlName="AuthorityNum" 
    (EmptyToNull) = "form.controls.AuthorityNum.value = $event">
    
    Run Code Online (Sandbox Code Playgroud)