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>
这是指令代码:
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
但是当我提交表单并检查 form.value 时,它再次显示为空字符串。
为什么?
更新:
这是我的提交功能:
onSubmit() {
 // TODO: Send to server
  this.form.value.AuthorityNum === '' // true
  }
这是 stackblitz 的代码: https://stackblitz.com/edit/angular-ilcg7y
您的代码有几个问题:
该指令需要发回值,以便可以绑定到相应的表单控件:
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">
| 归档时间: | 
 | 
| 查看次数: | 24324 次 | 
| 最近记录: |