I have an object that should build a form
const textBox = {
fontColor: 'red',
fontSize: '20',
placeholder: 'name',
name: 'input name',
label: 'mohamed',
validation: {
required: true
}
};
I created a simple dynamic form but I need to set the validators with each form control
ngOnInit(): void {
const inputDataObj = {} as any;
for (const prop of Object.keys(this.InputObj)) {
debugger;
if (prop !== 'validation') {
inputDataObj[prop] = new FormControl(this.InputObj[prop]);
this.inputProps.push(prop);
}
}
this.form = new FormGroup(inputDataObj);
}
now I need to set validation to any form control, the validation is an optional property,
some objects may not have any validations
2
Answers
I take it that you’d like to add validation only when the
required
property in yourvalidation
object is set to true.If so, you want to first create the
FormControl
and then use theaddValidators
method to dynamically add validation:Stacblitz
// Your component
// service (is better if you split your functionality in a service)