Angular 模板表单:如果表单未更改则禁用提交

Angular template form : disable submit if form didn't change

这是我的代码

          <form (ngSubmit)="onSubmit()" #f="ngForm">
            <input placeholder="Order ID" type="text" id="orderId" class="form-control" 
            name="orderId" [(ngModel)]="orderId" required>
            <button class="btn btn-primary" type="submit" [disabled]="!(f.valid && f.dirty)">Search</button>
          </form>

我原以为如果输入没有改变,按钮会被禁用,但事实并非如此。有谁知道为什么?

dirty / ! pristine means the user has made a modification

在您的情况下,如果您输入某些内容然后将其恢复为原始值,表单仍将保持

要检查是否有任何差异,您需要实现自己的方法。

Demo

正如罗伯特所说,您可以“玩”原始状态。例如

<form [formGroup]="form">
  <input formControlName="control">
  <button (click)="submit(form)" 
          [disabled]="!form.valid || form.pristine">submit</button>
</form>

  submit(form)
  {
    if (form.valid) //if valid mark as "pristine"
    {
      form.markAsPristine();
      console.log("submited") //do something
    }
    else
      form.markAllAsTouched(); //mark all the controls as touched
                               //to show the errors
  }

stackblitz