【问题标题】:Angular: Custom Form Validator Not Showing Mat ErrorAngular:自定义表单验证器不显示垫子错误
【发布时间】:2021-07-20 08:53:53
【问题描述】:

我要做的就是让用户在输入框中输入公司名称,然后调用一个简单的后端 api 来检查公司是否存在。

我的 API 调用工作正常,并在用户键入值时成功返回“true”或“false”。当它为假/公司不存在时,它只是不会在屏幕上显示错误。

带有“************”的部分是它没有返回任何东西的地方。没有编译错误或运行时错误,只是在公司不存在时不显示 mat 错误。

如果考虑到代码行数,我不怪你,如果你认为这是一个令人生畏的问题,我一直在尝试找出一个看似简单的问题,但花了将近 6 个小时。

我的报告-view.component.ts 文件:

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

@Component({
    selector: 'app-reports-view',
    templateUrl: './reports-view.component.html',
    styleUrls: ['./reports-view.component.scss']
})
export class ReportsViewComponent implements OnInit {
    matcher = new MyErrorStateMatcher();

    CompanyNameInputForm: FormGroup;

    companyNameValidator() {
        return (form: FormGroup) => {
            this.reportsPageService.doesCompanyNameExist(form.controls.companyName.value).subscribe((data) => {
                console.log(data);
                if (form.controls.companyName.value === "") {
                    console.log("returning null inside if");
                    return null;
                }
                else if (data==false) {
                    console.log("company name does not exist");

                    ******************return { invalidCompanyName: true };******************

                }
                console.log("returning null at end");
                return null;
            });
        }
        
    }
    ngOnInit() {

        this.CompanyNameInputForm = this.formBuilder.group(
            {
                companyName: [""]
            },
            { validator: this.companyNameValidator() }
        );
    
        this.CompanyNameInputForm.setValue({
            companyName: this.companyName
        });
    }
   constructor(private routingService: RoutingService, public reportsPageService: ReportsPageService, 
    private formBuilder: FormBuilder) {
        this.BASE_URL = routingService.getBaseUrl();
    }
}

在我的服务文件中:

doesCompanyNameExist(companyName: string):any {
        return this.http.post(`${this.BASE_URL}/RESTAPI/reports/doesCompanyNameExist?companyName=${companyName}`,
        this.httpOptions);
}

html:

<form [formGroup]="CompanyNameInputForm">
      <mat-form-field>
            <input matInput placeholder="Company name" type="text" formControlName="companyName" [errorStateMatcher]="matcher">
             <mat-error *ngIf="CompanyNameInputForm.hasError('invalidCompanyName')">Company does not exist
             </mat-error>
      </mat-form-field>
</form>

【问题讨论】:

  • companyNameValidator 的哪些日志实际显示在控制台中?
  • @DimitarSpassov console.log("公司名称不存在");
  • 您能否检查一下我在下面提供的答案是否解决了这个问题?

标签: angular forms validation input angular-material


【解决方案1】:

您正在尝试同步验证表单组,而验证结果是在异步签入您的服务之后。

您需要创建AsyncValidator 并更新FormGroup 的配置。

这意味着您必须像这样构建组:

 this.CompanyNameInputForm = this.formBuilder.group(
  {
   companyName: [""],
  },
  { asyncValidator: this.companyNameValidator }
 );

然后你需要更新验证器方法:

  companyNameValidator(form: FormGroup): Observable<ValidationErrors | null> {
    return this.reportsPageService.doesCompanyNameExist(form.controls.companyName.value)
      .pipe(map((data) => {
        console.log(data);
        if (form.controls.companyName.value === "") {
          console.log("returning null inside if");
          return null;
        }
        else if (data == false) {
          console.log("company name does not exist");
          return { invalidCompanyName: true };
        }
        console.log("returning null at end");
        return null;
      }));
  }

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 2014-12-24
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2019-02-12
    相关资源
    最近更新 更多