ErrorStateMatcher для проверки, если пароль == verifyPassword не работает правильно - PullRequest
0 голосов
/ 07 декабря 2018

Моя проблема: я реализовал ErrorStateMatcher в Angular, чтобы проверить, совпадает ли введенный пароль в форме с подтверждающим паролем.Это работает, но проблема в том, что поле verifyPassword отображается красным, пока форма полностью не заполнена.

нижнее правое поле здесь не заполнено: enter image description here

когда все заполнено, поле verifyPassword больше не красное: 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 голосов
/ 20 апреля 2019

Только что изменили 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);
  }
}
0 голосов
/ 07 декабря 2018

Изменения: *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

...