如何检查Angular响应式表单是否有任何价值?



我有一个有5个控件的Angular响应式表单。除此之外,我还有一个重置按钮。当重置按钮被点击时,如果表单不是空的,我想显示一个确认对话框。如果表单为空,我将简单地重置表单。

有没有办法检查反应表单是否为空白或有任何值?

this.userForm = this._formBuilder.group({
id: new FormControl(''),
isAdmin: new FormControl(false, [Validators.required]),
name: new FormControl('', [Validators.required]),
address: new FormControl('', [Validators.required]),
details: new FormControl(''),
});

你可以使用FormGroup的dirty属性:

this.userForm.dirty
const form = this.fb.group({
id: new FormControl(''),
isAdmin: new FormControl(false, [Validators.required]),
name: new FormControl('', [Validators.required]),
address: new FormControl('', [Validators.required]),
details: new FormControl(''),
});
const formValue = form.value;
// Although in this case it'd be semantically better to use .reduce, but for the sake of simplicity I'd prefer to use combination of .map + .some. If you're not afraid of .reduce, you can apply it here. 
const mapped = Object.values(formValue).map(value => !!value);
const hasValues = mapped.some(value => value);

但是也许你正在寻找另一种解决方案(只是为了检查表单是否被触摸)。在这种情况下,你可以坚持形式。Dirty(尽管如果用户删除之前输入的数据将无法工作)或form.invalid.

也许你正在寻找这个:

onSave(): void {
// stop here if form is invalid
if (this.userForm.invalid) {
return;
}
// do what you want to save
}

相关内容

最新更新