使用 Angular Material 处理服务器端错误

Handle server side error with Angular Material

我有一个表单,我这样处理服务器端错误。

  constructor(private store: Store<fromRoot.State>) {
    this.containerTypes$ = store.pipe(select(fromWelcome.getCts));
    this.errors$ = store.pipe(select(fromModal.getError) as any);
    this.errors$.subscribe(errors => {
      if (errors) {
        if (errors.username) {
          this.usernameError = errors.username;
          this.regForm.controls['username'].setErrors({usernameServerError: this.usernameError});
          // <-------- I want to call my mat-error here
        }
      }
    }
    );

    this.regForm = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.minLength(5)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8)])
    });

在 .html 我这样做:

<mat-error *ngIf="regForm.controls['username'].hasError('usernameServerError')"> {{usernameError}} </mat-error>

不幸的是,我在尝试提交后遇到错误,但我的输入没有出现。我需要先点击输入,或者再次提交表单。如何在我的表单中收到错误后立即显示?

我需要启用我的表单

  constructor(private store: Store<fromRoot.State>) {
    this.containerTypes$ = store.pipe(select(fromWelcome.getCts));
    this.errors$ = store.pipe(select(fromModal.getError) as any);
    this.errors$.subscribe(errors => {
      if (errors) {
        this.regForm.enable() // <---- here
        if (errors.username) {
          this.usernameError = errors.username;
          this.regForm.controls['username'].setErrors({usernameServerError: this.usernameError});
        }
      }
    }
    );

    this.regForm = new FormGroup({
      username: new FormControl('', [Validators.required, Validators.minLength(5)]),
      email: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8)])
    });