首页 > 解决方案 > 根据条件对表单进行角度所需的验证

问题描述

我的代码有一部分,我只根据需要设置一些字段。默认情况下,只有 emailAddress 是必填字段,但我的应用中有条件根据需要设置 firstName 、 lastName 、 companyName 。

如果 res.isSuccess === true 那是我只想根据需要设置 firstname , lastname , company name 的时间。

但问题是,正如您在下面的屏幕显示中看到的那样,mat 错误消息已经在初始加载时显示(红色的)它应该只显示例如 firstname 字段被触摸或单击,因此默认情况下不应该显示该消息。

关于这个问题的任何想法?谢谢你。

#html

 <mat-form-field class="full-width" appearance="fill" style="margin-top: 26px;">
                                <mat-label>First Name *</mat-label>
                                <input matInput formControlName="firstName">
                                <mat-error
                                    *ngIf="modelForm.get('firstName').hasError('required')  && (modelForm.get('firstName').touched || modelForm.get('firstName').dirty)">
                                    First Name is required.
                                </mat-error>
                            </mat-form-field>

     getStarted() {
        this.AccountRoleDetails = null;
        if (this.userService) {
          this.userService
            .getUserEmail(this.accountId, this.modelForm.value['emailAddress'])
            .subscribe(
              (res: any) => {
                if (
                  res.isSuccess === true 
                ) 
              this.setRequiredVlidations();
    
    
    {
.........

#代码

initFormGroup() {
    this.modelForm = this.formBuilder.group({
      id: [this.model.id || 0],
      emailAddress: [this.model.emailAddress, Validators.required],
      firstName: this.model.firstName,
      roleId: this.model.roleId,
      lastName: this.model.lastName,
      phoneNumber: this.model.phoneNumber,
      companyName: this.model.companyName,
    });
  }

#代码 2

setRequiredVlidations() {
    this.modelForm.get('firstName').setValidators(Validators.required);
    this.modelForm.get('lastName').setValidators(Validators.required);
    this.modelForm.get('companyName').setValidators(Validators.required);

    this.modelForm.updateValueAndValidity();
  }

在此处输入图像描述

标签: angulartypescriptangular-material

解决方案


尝试取出

this.modelForm.updateValueAndValidity();

这可能会导致 Angular Reactive 表单检查该值,如果它是空的,如果它是“必需的”,它将是无效的。

在您的 mat-error html 标记中,尝试分离出该逻辑树以更清晰:

<mat-error *ngIf="(modelForm.get('firstName').hasError('required') && 
    modelForm.get('firstName').touched) || 
    modelForm.get('firstName').dirty">
        First Name is required.
</mat-error>

您也可以尝试在此处更改您的逻辑:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.dirty">
        First Name is required.
</mat-error>

或者:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.touched">
        First Name is required.
</mat-error>

取决于您的 UI/UX 要求。

这将帮助您更清楚地了解它返回无效状态的确切原因。使用浏览器控制台并进行一些检查。

还可以尝试使用您的浏览器工具在设置新验证器之前和之后实际查看表单字段验证错误和值以及该字段的有效性状态。“必需”状态的访问方式可能与您的访问方式不同。

您可以发布从浏览器控制台获得的这些值并更新您的问题吗?


推荐阅读