Angular 6 反应式表单验证不起作用

Angular 6 Reactive Form Validationdoesn't work

我正在编写简单的登录表单,尝试结合这两个教程:

但我卡住了。验证未按预期工作。我通过从组件向模板发送 "message"(即值,当我检查 loginForm.value)来解决问题,但这不是它应该如何工作的。我哪里做错了?

以下是我无法实现的部分代码:


login.component.html

<div class="container">
  <div class="col-md-6">
    <h2>Log In</h2>
    <hr>
    <p *ngIf="message" class="text-center error">{{message}}</p>
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

      <div class="form-group clearfix" [ngClass]="{ 'has-error': submitted && f.userid.errors }">
        <label for="userid" class="col-md-3 col-sm-5 col-xs-12">Userid</label>

        <div class="col-md-9 col-sm-7 col-xs-12">
          <input type="text" class="form-control" formControlName="userid" />
          <div *ngIf="submitted && f.userid.errors" class="help-block">
            <div *ngIf="f.userid.errors.required">Userid is required</div>
          </div>
        </div>
      </div>

      <div class="form-group clearfix" [ngClass]="{ 'has-error': submitted && f.password.errors }">
        <label for="password" class="col-md-3 col-sm-5 col-xs-12">Password</label>

        <div class="col-md-9 col-sm-7 col-xs-12">
          <input type="password" class="form-control" formControlName="password" />
          <div *ngIf="submitted && f.password.errors" class="help-block">
            <div *ngIf="f.password.errors.required">Password is required</div>
          </div>
        </div>
      </div>

      <div class="col-xs-12 form-group text-right">
        <button class="btn btn-success" type="submit">Login</button>
      </div>

    </form>
  </div>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Login } from '../login';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  model: Login = { userid: "admin", password: "nenad123" };
  loginForm: FormGroup;
  message: string;
  returnUrl: string;

  constructor(private formBuilder: FormBuilder, private router: Router, public authService: AuthService) { }

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

    this.returnUrl = '/home';
    this.authService.logout();
  }

  get f() { return this.loginForm.controls; }

  onSubmit() {

    if (this.loginForm.invalid) {
      let user = this.loginForm.value.userid;
      let pass = this.loginForm.value.password;
      if (user == "" && pass == "") { this.message = "UserId and Password cannot be empty"; }
      else if (user == "") { this.message = "UserId cannot be empty"; }
      else if (pass == "") { this.message = "Password cannot be empty"; }
      else { this.message = "Please check your userid and password"; }
      return;
    }
    else {
      if (this.f.userid.value == this.model.userid && this.f.password.value == this.model.password) {
        localStorage.setItem('isLoggedIn', "true");
        localStorage.setItem('token', this.f.userid.value);
        this.router.navigate([this.returnUrl]);
      }
      else {
        this.message = "Please check your userid and password";
      }
    }
  }

}

这部分是临时解决方法:

if (this.loginForm.invalid) {
      let user = this.loginForm.value.userid;
      let pass = this.loginForm.value.password;
      if (user == "" && pass == "") { this.message = "UserId and Password cannot be empty"; }
      else if (user == "") { this.message = "UserId cannot be empty"; }
      else if (pass == "") { this.message = "Password cannot be empty"; }
      else { this.message = "Please check your userid and password"; }
      return;
    }

在您的 html 中,您正在使用 *ngIf="submitted && .... 但我没有看到已提交设置 onSubmit()

    onSubmit() {
        this.submitted = true;
        // rest of code goes here
    }

您可以考虑将其添加到 onSubmit() 方法中

此外,您可以在字段被触摸和弄脏后检查验证

*ngIf="(f.dirty || f.touched) && f.errors"