0

I am creating a FormGroup with a set of FormControls with an array of objects like this :

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 setValidators.required based on the JSON object. Something like this :

[fieldMetaData.formFieldName]: new FormControl('' , fieldMetaData.required ? Validators.required : null )}), {});

How can I achieve that?

1 Answer 1

1

Try with this.

new FormControl('' , fieldMetaData.required ? [Validators.required] : [])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.