Ser*_*gey 2 validation form-control reactive-forms angular
有没有办法检查是否需要控制?
当我实现它接受一个专用表单字段部件的问题出现FormControl,并不仅input也验证错误。由于某些字段是必填字段,因此最好让用户知道是否需要*。
有没有一种方法来检查@Input() control: FormControl的Validators.required,并显示一个星号?
您可以执行以下操作:
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。
我需要一些更抽象的内容,因此我对@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)
根据这个Angular 文档,您可以使用 hasValidator 方法来检查控件中是否使用了内置验证器。
let abstractControl = this.formGroup.controls[this.formControlName];
const isRequired = abstractControl.hasValidator(Validators.required);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5864 次 |
| 最近记录: |