为什么在反应形式中将空字符串设置为 null 变成空字符串
Why set empty string as null in reactive form become empty string
我正在尝试在 cahnge 时将每个字符串输入转换为 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
我正在尝试使用 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);
希望对您有所帮助!
您的代码有几个问题:
指令需要发回值,以便可以绑定到相应的表单控件:
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">
指令代码:
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>
我正在尝试在 cahnge 时将每个字符串输入转换为 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
我正在尝试使用 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);
希望对您有所帮助!
您的代码有几个问题:
指令需要发回值,以便可以绑定到相应的表单控件:
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">
指令代码:
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>