[英]Dynamic Validations for Form Control in Reactive Forms - Angular 7
I am creating a FormGroup with a set of FormControls with an array of objects like this :我正在创建一个带有一组 FormControls 的 FormGroup,其中包含一组像这样的对象:
import { Component, OnInit } from '@angular/core'
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class App implements OnInit {
formData : Array<{type:string , formFieldName:string , required?: boolean } = [
{
type : 'text',
formFieldName:'field1',
required : true
},
{
type : 'text',
formFieldName:'field2',
required : true
},{
type : 'text',
formFieldName:'field3',
},
];
ngOnInit() {
const formFields = this.formData.reduce(
(formObj, fieldMetaData) => Object.assign(formObj, {
[fieldMetaData.formFieldName]: new FormControl('' , Validators.required )}), {});
this.form = new FormGroup(formFields);
}
}
I have to set Validators.required
based on the JSON object.我必须根据 JSON 对象设置
Validators.required
。 Something like this :像这样的事情:
[fieldMetaData.formFieldName]: new FormControl('' , fieldMetaData.required ? Validators.required : null )}), {});
How can I achieve that?我怎样才能做到这一点?
试试这个。
new FormControl('' , fieldMetaData.required ? [Validators.required] : [])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.