我正在尝试将每个输入的字符串转换为空。 因此,我创建了一个指令来侦听每个更改,并将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
答案 0 :(得分:1)
您的代码有几个问题:
指令需要将值传回,以便可以绑定到相应的表单控件:
export class NullValueDirectiveDirective {
@Output('EmptyToNull') response = new EventEmitter<string>();
@HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) {
this.response.emit(null);
}
}
下一步,在模板上,您需要绑定到 emitted 值:
<input formControlName="AuthorityNum"
(EmptyToNull) = "form.controls.AuthorityNum.value = $event">
答案 1 :(得分:0)
我正在尝试使用EmptyToNull指令来了解您的目标。
如果您试图避免在表单中传递空值,则在ts中构建表单时可以更好地使用验证器:
this.form = this.formbuilder.group({
date: [''],
AuthorityNum: ['', [Validators.required]],
});
有关验证程序的更多信息:https://angular.io/api/forms/Validators
提交表单时,您还可以检查所填满的验证器的值:
onSubmit() {
Object.keys(this.form.controls).forEach(field => {
let control = this.form.get(field);
control.markAsTouched({
onlySelf: true
});
control.updateValueAndValidity();
});
}
在提交表单或检测表单中的更改时,您也可以在TS中尝试以下方法:
this.form.reset({
date: { value: '' },
AuthorityNum: { value: null }
});
甚至在您的指令中应用
this.form.controls['AuthorityNum'].setValue(null);
希望有帮助!
答案 2 :(得分:0)
指令代码:
import { Directive, HostListener, Self } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({ selector: '[EmptyToNull]' })
export class EmptyToNullDirective {
constructor(@Self() private ngControl: NgControl) {}
@HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) {
if (this.ngControl.value?.trim() === '') {
this.ngControl.reset(null);
}
}
}
模板:
<input nbInput fullWidth fieldSize="small" shape="semi-round" formControlName="AuthorityNum" EmptyToNull>