首页 > 解决方案 > Angular 表单按钮在验证表单后未启用

问题描述

在进行一些更改时,我正在跟随 fireship 教程,但是当我的表单验证应该返回 true 时,我的提交按钮似乎没有从禁用切换到启用。

这就是我到目前为止在 html 中登录的内容

<form [formGroup]="loginForm" novalidate>
  <mat-form-field>
    <input matInput type="text" placeholder="email" #email required >
  </mat-form-field>
  <mat-form-field>
    <input matInput type="password" placeholder="Password" #password required>
  </mat-form-field>
  <div class="d-flex flex-column align-items-center">
    <!-- Calling SignIn Api from AuthService -->
      <button mat-raised-button  class="button is-success w-100" type="submit" 
        (click)="checkSignIn(email.value, password.value)">
        Continue
      </button>
  </div>
  <div *ngIf="email.invalid || password.invalid" class="notification is-danger">
    Something isn't right with the Email or Password
  </div>
</form>

在我的 ts

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', [
        Validators.required,
        Validators.email
      ]],
      password: ['',
        Validators.required
      ],
    });
  }

  // Use getters for cleaner HTML code
  get email() {
    return this.loginForm.get('email')
  }

  get password() {
    return this.loginForm.get('password')
  }
  checkSignIn(email, password) {
    if (this.authService.SignIn(email, password))
    {

    this.authService.SignIn(email, password);
    console.log("email or password is wrong");
    }
  }

[disabled]="!loginForm.valid"如果我从继续按钮中删除,当我键入错误的用户凭据时,控制台日志能够显示“电子邮件或密码错误” 。如果用户成功登录,我也能够成功进入下一页。但是,当我在表单无效时禁用它时,当我键入电子邮件并填写密码时,它似乎并没有启用。也没有错误信息。

我可能错过了什么阻止登录表单验证

标签: angularvalidation

解决方案


在 Angular 2 到所有其余版本中,您可以使用以下代码在 html 文件更改中并仅添加 [disabled]="loginForm.form.invalid"。

<form #loginForm="ngForm"> 
  <button  [disabled]="loginForm.form.invalid" mat-raised-button  class="button is-success w-100" type="submit" 
    (click)="checkSignIn(email.value, password.value)">
    Continue
  </button>
</form>

在 ts 文件中添加:

loginForm : FormGroup;

推荐阅读