Angular FormControl检查(如果需要)

Ser*_*gey 2 validation form-control reactive-forms angular

有没有办法检查是否需要控制?

当我实现它接受一个专用表单字段部件的问题出现FormControl,并不仅input也验证错误。由于某些字段是必填字段,因此最好让用户知道是否需要*

有没有一种方法来检查@Input() control: FormControlValidators.required,并显示一个星号?

Sid*_*era 5

您可以执行以下操作:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms';

@Component({...})
export class AppComponent  {
  form: FormGroup = new FormGroup({
    control: new FormControl(null, Validators.required)
  });

  get validator() {
    const validator = this.form.get('control').validator({} as AbstractControl);
    console.log(validator);
    if (validator && validator.required) {
      return true;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的模板中:

<form [formGroup]="form" (submit)="onSubmit()">
  Control: <span *ngIf="validator">*</span> <input type="text" formControlName="control">
  <button>Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)

注意:只需将窗体控件作为AbstractControl使用此控件的一种类型即可this.form.get('control').validator({} as AbstractControl);

这将返回一个Object,其中包含您的上存在的验证器列表FormControl。然后,您可以required在对象中检查密钥。如果它存在且其值为,true则可以确保在上应用了必填验证器FormControl


这是供您参考的工作样本StackBlitz


ran*_*ame 5

我需要一些更抽象的内容,因此我对@siddajmera的答案进行了一些修改,以便可以在任何字段中使用。

在您的.ts文件中:

isRequiredField(field: string) {
    const form_field = this.testForm.get(field);
    if (!form_field.validator) {
        return false;
    }

    const validator = form_field.validator({} as AbstractControl);
    return (validator && validator.required);
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的模板文件中:

<div>
    <label>Some Field:<span *ngIf="isRequiredField('some_field')">*</span></label>
    <input [formControl]="form.controls['some_field']">
</div>
<div>
    <label>Some Field:<span *ngIf="isRequiredField('another_field')">*</span></label>
    <input [formControl]="form.controls['another_field']">
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这个答案比批准的答案好一点,因为它减少了“ERROR TypeError: form_field.validator is not a function”的可能性,只需将默认值设置为 getter 方法即可。 (2认同)

Ami*_*aei 5

根据这个Angular 文档,您可以使用 hasValidator 方法来检查控件中是否使用了内置验证器。

let abstractControl = this.formGroup.controls[this.formControlName];
const isRequired = abstractControl.hasValidator(Validators.required);
Run Code Online (Sandbox Code Playgroud)