Angular ControlValueAccessor必需属性

问题描述 投票:0回答:2

我有一个实现ControlValueAccessor的文本框控件。在表单中,我在表单字段名称上放置了一个必需的验证器:

 this.formGroup = this.fb.group({
        name: ['', Validators.required]
    });

在模板中我使用这样的控件:

<input-text formControlName="name"></input>

Angular需要验证,但内部文本框没有必需的属性。如果需要,我想设置这个文本框的样式,我该如何做到这一点?

angular validation required controlvalueaccessor
2个回答
0
投票

您需要检查表单控件的值更改,如下所示

this.control.valueChanges.subscribe(
            (res) => {
                this.setErrorMessage(this.control);
            }
        )

然后在setErrorMessage里面检查control.errors

if (control.errors) {
  for (let propertyName in control.errors) {
    if(propertyName == "required") {
      // you can do things here to your input field by using element reference
    }
  }
}

我创建了一个函数来知道输入字段是否为dirt = y

//Validate single field
export function isInputFieldDirty(controlName: string, formGroupObject: FormGroup) {
if (formGroupObject.get(controlName)) {
    return !formGroupObject.get(controlName).pristine &&
        ((formGroupObject.get(controlName).untouched && formGroupObject.get(controlName).dirty && formGroupObject.get(controlName).invalid) ||
            (formGroupObject.get(controlName).touched && formGroupObject.get(controlName).invalid))
        ? true : false;
}

}


0
投票

如果要在控件具有必需验证器的情况下设置字段样式,则可以使用此实用程序:

  isRequired(formControl: AbstractControl): boolean {
    return this.hasRequiredField(formControl);
  }
  hasRequiredField = (abstractControl: AbstractControl): boolean => {
    // caso formControl
    if (abstractControl.validator) {
      const validator = abstractControl.validator({} as AbstractControl);
      if (validator && validator.required) {
        return true;
      }
    } // caso formGroup
    if (abstractControl['controls']) {
      for (const controlName in abstractControl['controls']) {
        if (abstractControl['controls'][controlName]) {
          if (this.hasRequiredField(abstractControl['controls'][controlName])) {
            return true;
          }
        }
      }
    }
    return false;
  }

在你的控制器中

isRequired(formControlName){
    isRequired(formControlName: string): boolean {
        return this.utils.isRequired(this.form.get(formControlName));
    }
}

如果要在字段无效时显示消息并应用样式,则可以使用简单的“有效”属性当字段无效时显示消息错误,对象返回hasError('required')

现在,如果你想要风格

<label> Name {{isRequired('name') ? '*' :'' }} </label>
<input-text formControlName="name" [ngClass]="{'required': isRequired('name'), 'notValid' : !this.form.get('name').valid  }"></input>

<span class="help-block error" *ngIf="((form.get('name').touched || form.get('name').dirty) && !form.get('name').valid)">
        <span *ngIf="form.get('name').hasError('required')">
            {{ 'ERROR_MSG.REQUIRED' | translate }}
        </span>
        <span *ngIf="form.get('name').hasError('maxlength')">
            {{ 'ERROR_MSG.MAXLENGTH' | translate }} {{getError('maxlength').requiredLength}}
        </span>
        <span *ngIf="form.get('name').hasError('minlength')">
            {{ 'ERROR_MSG.MINLENGTH' | translate }} {{getError('minlength').requiredLength}}
        </span>

        <span *ngIf="form.get('name').hasError('myCustomError')">
            {{ 'ERROR_MSG.CUSTOM' | translate }}
        </span>
    </span>
</div>

getError(error: string) {
    return this.form.controls['name'].errors[error];
  }
© www.soinside.com 2019 - 2024. All rights reserved.