Angular FormControl检查(如果需要) [英] Angular FormControl check if required

查看:534
本文介绍了Angular FormControl检查(如果需要)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查是否需要控制?

Is there a way to check whether control is required?

当我实现了一个接受FormControl并且不仅具有input而且具有验证错误的专用表单域组件时,出现了问题.由于需要某些字段,因此最好让用户知道*是否需要.

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

是否可以检查@Input() control: FormControl中的Validators.required并显示星号?

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

推荐答案

您可以执行以下操作:

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

然后在您的模板中:

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


注意:只需使用此this.form.get('control').validator({} as AbstractControl);


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

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

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.

这篇关于Angular FormControl检查(如果需要)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆