samedi 23 mars 2019

How to apply required validation for checkbox using dynamically

I'm setting dynamic form validation using the following JSON. base on these JSON i have create dynamically form field using the following JSON format.

Data

  fields = [
    {
      type: 'text',
      name: 'firstName',
      label: 'First Name',
      value: '',
      required: true,
   },
   {
      type: 'checkbox',
      name: 'hobby',
      label: 'Hobby',
      required: true,
      options: [
        { key: 'f', label: 'Fishing' },
        { key: 'c', label: 'Cooking' }
      ]
    }
  ]

My commponent.ts file is following

form: FormGroup;

ngOnInit() {
  let fieldsCtrls = {};
    for (let f of this.fields) {
      if (f.type != 'checkbox') {
        fieldsCtrls[f.name] = new FormControl(f.value || '', 
          Validators.required)
      } else {
        let opts = {};
        for (let opt of f.options) {
          opts[opt.key] = new FormControl(opt.value);
        }
       fieldsCtrls[f.name] = new FormGroup(opts)
     }
   }
   this.form = new FormGroup(fieldsCtrls);
}  

I have apply required validation for all input field exclude checkbox.

How can apply required validation for the checkbox in this code?




Aucun commentaire:

Enregistrer un commentaire