Angular FormControl check if required

断了今生、忘了曾经 提交于 2019-12-11 02:26:49

问题


Is there a way to check whether control is required?

The problem arose when I implemented a dedicated form field component which accepts FormControl and has not only input but also validation errors. Since some field are required it's good to let the user know if it's required by *.

Is there a way to check the @Input() control: FormControl for Validators.required and display an asterisk?


回答1:


You can do something like this:

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;
    }
  }
}

And then in your Template:

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

NOTE: Just get the form control as a type of AbstractControl using this this.form.get('control').validator({} as AbstractControl);

This will return an Object with the list of validators that are present on your FormControl. You can then check for the required key in the Object. If it exists and its value is true then you can be sure that a Required Validator is applied on the FormControl.


Here's a Working Sample StackBlitz for your ref.




回答2:


I needed something slightly more abstract, so I've adapted the answer from @siddajmera a bit to be able to use on any field.

In your .ts file:

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);
}

Then, in your template file:

<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>


来源:https://stackoverflow.com/questions/53557690/angular-formcontrol-check-if-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!