ErrorStateMatcher验证密码== ConfirmPassword是否无法正常工作

时间:2018-12-07 09:07:53

标签: html angular validation angular-material angular6

我的问题: 我在Angular中实现了ErrorStateMatcher,以验证表单中输入的密码是否与ConfirmPassword相同。 它可以工作,但是问题是,confirmPassword字段显示为红色,直到表单完全填写为止。

右下角的字段未在此处填写: enter image description here

当所有内容都填满时,confirmPassword字段不再是红色的: enter image description here

ErrorStateMatcher:

    export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(
    control: FormControl | null,
    form: FormGroupDirective | NgForm | null
  ): boolean {
    const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
    const invalidParent = !!(
      control &&
      control.parent &&
      control.parent.invalid &&
      control.parent.dirty
    );
    return invalidCtrl || invalidParent;
  }
}

component.ts:

export class AdminpanelComponent implements OnInit {
  constructor(
    private ts: TableService,
    private us: UserService,
    private as: AdminpanelService,
    private formBuilder: FormBuilder
  ) {
    this.registerForm = this.formBuilder.group(
      {
        email: new FormControl(
          "",
          Validators.compose([
            Validators.required,
            ValidationService.emailValidator
          ])
        ),
        password: new FormControl(
          "",
          Validators.compose([
            Validators.required,
              ValidationService.passwordValidator
          ])
        ),
        confirmPassword: new FormControl("", Validators.required),
        firstName: new FormControl("", Validators.required),
        lastName: new FormControl("", Validators.required),
        permission: new FormControl("", Validators.required)
      },
      { validator: this.checkPasswords }
    );
  matcher = new MyErrorStateMatcher();
userList: UserRegister[] = [];
  userRegister!: UserRegister;

  submitUser() {
    this.userRegister = Object.assign({}, this.registerForm.value);
    this.us.registerUser(this.userRegister);
    this.userList.push(this.userRegister);
  }
  get form() {
    return this.registerForm.controls;
  }
  checkPasswords(group: FormGroup) {
    let pass = group.controls.password.value;
    let confirmPass = group.controls.confirmPassword.value;
    return pass === confirmPass ? null : { notSame: true };
  }
}

component.html:

      <mat-tab>
        <ng-template mat-tab-label>
          <mat-icon class="example-tab-icon">person_add</mat-icon>
          Neuer Benutzer
        </ng-template>

        <form [formGroup]="registerForm" class="usercreation-form" (ngSubmit)="submitUser()">
          <table class="example-full-width" cellspacing="0">
            <tr>
              <td>
                <mat-form-field class="example-full-width">
                  <input id="firstName" matInput placeholder="Vorname" formControlName="firstName" required>
                  <mat-error *ngIf="registerForm.hasError('required')">
                    Please enter your first name
                  </mat-error>
                </mat-form-field>
              </td>
              <td>
                <mat-form-field class="example-full-width">
                  <input matInput placeholder="Name" formControlName="lastName" required>
                  <mat-error *ngIf="registerForm.hasError('required')">
                    Please enter your last name
                  </mat-error>
                </mat-form-field>
              </td>
            </tr>
          </table>

          <table class="example-full-width" cellspacing="0">
            <tr>
              <td>
                <mat-form-field class="example-full-width">
                  <input type="password" matInput placeholder="Passwort" formControlName="password">
                  <mat-error *ngIf="registerForm.hasError('required', 'password')">
                    Please enter your password
                  </mat-error>
                </mat-form-field>
              </td>
              <td>
                <mat-form-field class="example-full-width">
                  <input type="password" matInput placeholder="Passwort bestätigen" formControlName="confirmPassword"
                    [errorStateMatcher]="matcher">
                  <mat-error *ngIf="registerForm.hasError('required', 'notSame')">
                    Passwords do not match
                  </mat-error>
                </mat-form-field>
              </td>
            </tr>
          </table>

          <table class="example-full-width" cellspacing="0">
            <tr>
              <td>
                <mat-form-field class="example-full-width">
                  <input id="email" type="email" matInput placeholder="Email" formControlName="email" required>
                  <mat-error>
                    wrong email format
                  </mat-error>
                </mat-form-field>
              </td>
              <td>
                <mat-form-field class="example-full-width">
                  <mat-select placeholder="Berechtigung" formControlName="permission">
                    <mat-option value="user">Benutzer</mat-option>
                    <mat-option value="admin">Administrator</mat-option>
                  </mat-select>
                  <mat-error *ngIf="registerForm.controls['permission'].hasError('required') && registerForm.controls['permission'].pristine">
                    please choose the permission
                  </mat-error>
                </mat-form-field>
              </td>
            </tr>
          </table>
          <button type="submit" [disabled]="!registerForm.valid">submit</button>
        </form>
      </mat-tab>
    </mat-tab-group>
  </mat-tab>

提前谢谢!

2 个答案:

答案 0 :(得分:1)

更改: *ngIf="registerForm.hasError('required', 'password')"*ngIf="registerForm['controls'].password.hasError('required', 'password')"

               <mat-form-field class="example-full-width">
                  <input type="password" matInput placeholder="Passwort" formControlName="password">
                  <mat-error *ngIf="registerForm['controls'].password.hasError('required', 'password')">
                    Please enter your password
                  </mat-error>
                </mat-form-field>

confirmPassword

执行相同操作

答案 1 :(得分:1)

只需将MyErrorStateMatcher更改为此即可,现在它可以工作了:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidParent = !!(
      control
      && control.parent
      && control.parent.invalid
      && control.parent.dirty
      && control.parent.hasError('notSame'));
    return (invalidParent);
  }
}