如何检查 Angular 反应形式是否有任何价值?

how to Check if Angular Reactive form has any value?

我有一个带有 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 的脏 属性 :

this.userForm.dirty

也许您正在寻找这个:

onSave(): void {
    // stop here if form is invalid
    if (this.userForm.invalid) {
        return;
    }

    // do what you want to save
}

此致

    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);

但也许您正在寻找另一种解决方案(只是为了检查表单是否被触及)。在这种情况下,您可以坚持使用 form.dirty(尽管如果用户删除之前输入的数据,它就不起作用)或 form.invalid.