验证器和错误在 Angular 9 中不起作用

The Validators And Errors Are Not Working In Angular 9

我已经开始研究 Angular 9,我在 Angular 9 中使用响应式表单,但问题是验证器和错误不适用于表单。

这是我的 app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是我的 app.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { MustMatch } from './_helpers/must-match.validator';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'my-assignment';
  submitted = false;
  show: boolean;
  profileForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.show = true;
  }

  ngOnInit() {
    this.profileForm = this.fb.group({
    email: ['', [Validators.required, Validators.pattern('[a-z0-9.@]*')]],
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirmpassword: ['', Validators.required],
  },  {
        validator: MustMatch('password', 'confirmpassword')
      });
  }

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

  onSubmit() {
  // TODO: Use EventEmitter with form value
  console.warn(this.profileForm.value);
  }
  
  // click event function toggle
   password() {
    this.show = !this.show;
  }
}

这是我的 app.component.html:

<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <form style="margin-top: 100px;" [formGroup]="profileForm" (ngSubmit)="onSubmit()">

                    <div class="form-group">
                        <label for="firstName">Email: </label>
                        <input type="text" placeholder="Email" formControlName="email">
                        <div *ngIf="f.email.hasError('pattern')">
                            Oops, wrong pattern buddy!
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="password">Password: </label>
                        <input [type]="show ? 'text' : 'password'" placeholder="Password" formControlName="password">
                        <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                            <div *ngIf="f.password.errors.required">Password is required</div>
                            <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="confirmpassword">Confirm Password: </label>
                        <input type="password" placeholder="Confirm Password" formControlName="confirmpassword" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.confirmPassword.errors }" />
                        <div *ngIf="submitted && f.confirmpassword.errors" class="invalid-feedback">
                            <div *ngIf="f.confirmpassword.errors.required">Confirm Password is required</div>
                            <div *ngIf="f.confirmpassword.errors.mustMatch">Passwords must match</div>
                        </div>
                    </div>
                    <button (click)="password()">Show Password</button>
                    <button type="submit" [disabled]="!profileForm.valid">Submit</button>

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

这是我的 must-match.validator.ts:

import { FormGroup } from '@angular/forms';

// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            // return if another validator has already found an error on the matchingControl
            return;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
        } else {
            matchingControl.setErrors(null);
        }
    };
}

core.js:6185 ERROR TypeError: Cannot read property 'errors' of undefined

非常感谢任何帮助。

您有错字:confirmPassword ( *ngIf="f.confirmPassword.errors.required")。 其他地方都是confirmpassword