0

I am trying to make dynamic forms with Json data and the conditions should be selected from the options type selection from the JSON data. The JSON data structure are as follow. In this case for example, after selecting the the first element A Speditions GmbH from drop down the child content of this elements "label": "Subfield1", and another drop down options should be appear on the form.

My Typescript (Updated)

import { Component, OnInit } from '@angular/core'; 
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef } from '@angular/material';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    form:FormGroup;
    formTemplate:any = form_template;
    stepCfg = {
      stepType: 'rahmendaten',
      stepHeading: '',
      stepIndex: 0,
      steps: [],
      firstStep: false,
      lastStep: false,
      onlyStep: false,
      data: {},
      htmlContent: ''
    };
    formDataObj = {};


  ngOnInit() {
    for (const prop of Object.keys(this.stepCfg.data)) {
      this.formDataObj[prop] = new FormControl(this.stepCfg.data[prop].value);
      this.formTemplate.push({
        key: prop,
        label: this.stepCfg.data[prop].label,
        type: this.stepCfg.data[prop].type,
        options: this.stepCfg.data[prop].options
      });
    }
   this.form = new FormGroup(this.formDataObj);
  }
}

 const form_template = [{
 "type": "select",
 "label": "Spedition",
 "options": [
 {
     "value": "sped1",
     "label": "A Speditions GmbH",
     "subfield": {
        "type": "select",
        "label": "Subfield1",
        "options": [
          {
            "value": "subfieldvalue1",
            "label": "101"
          },
        ]
        }
     },
   {
      "value": "sped2",
      "label": "Alf Scon GmbH"
   },
  {
      "value": "sped3",
      "label": "Barthtest"
  },
 ]

}]

export default form_template

//HTml

<mat-card class="rahmendaten-container">
  <h3 class="page__header">{{stepCfg.stepHeading}}</h3>
  <div *ngIf="!!stepCfg.htmlContent" [innerHTML]="stepCfg.htmlContent"> 
  </div>
  <form [formGroup]="form" autocomplete="off" (ngSubmit)="onSubmit()">
    <mat-card-content class="page">
      <div class="page__container">
        <div *ngFor="let prop of formTemplate" class="container__row">
          <div [ngSwitch]="prop.type">
            <div *ngSwitchCase="'select'">
              <span [innerHTML]="prop.label" class="container__row__label"> 
              </span>
             <mat-form-field>
                <mat-select>
                  <mat-option *ngFor="let option of prop.options" 
                  [value]="option.value">{{option.label}}</mat-option>
                  </mat-select>
             </mat-form-field>
            </div>
          </div>
        </div>
      </div>
    </mat-card-content>
   </form>
  </mat-card>
2
  • You need to write a question. what part of doing your task is a problem? Commented Sep 18, 2019 at 7:46
  • @Vato I have to implement the conditions In this case for example, after selecting the the first element A Speditions GmbH from drop down the child content of this elements "label": "Subfield1", and another drop down options should be appear on the form. Commented Sep 18, 2019 at 8:10

1 Answer 1

1

Since you don't have much in your code. You need to do more work. I will just give you recommendations on what to do.

check reactive forms or template driven forms. I recommend reactive forms.

than actually you can transfer your form to reactive forms.

form_template = [{
    "type": "select",
    "label": "Spedition",
    "options": [
      {
        "value": "sped1",
        "label": "Adrian Speditions GmbH",
        "subfield": {
          "type": "select",
          "label": "Subfield1",
          "options": [
            {
              "value": "subfieldvalue1",
              "label": "101"
            },
          ]
        }
      },
      {
        "value": "sped2",
        "label": "Alfred Schuon GmbH"
      }
    ]
  }]

reactive form would look something like:

reactiveForm: FormGroup;

this.reactiveForm = new FormGroup({
  type: new FormControl('select'),
  label: new FormControl('Spedition'),
  options: new FormArray([
    new FormGroup({
      value: new FormControl('sped1'),
      label: new FormControl('Adrian Speditions GmbH'),
      subfield: new FormGroup({
        type: new FormControl('select'),
        label: new FormControl('Subfield1'),
        options: new FormArray([
          new FormGroup({
            value: new FormControl('subfieldvalue1'),
            label: new FormControl('101')
          })
        ])
      })
    })
  ])
});

you access and change values in TS like this.

this.reactiveForm.get('options').at(indexOfArray).get('value').setValue('Your New Value');

since you want to a use select. here is example from angular material webpage using reactive forms. Check: https://material.angular.io/components/select/examples also here is my dynamic forms qustion it also might help.

<h4>mat select</h4>
<mat-form-field>
  <mat-label>Favorite animal</mat-label>
  <mat-select [formControl]="animalControl" required>
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [value]="animal">
      {{animal.name}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>
  <mat-hint>{{animalControl.value?.sound}}</mat-hint>
</mat-form-field>

to bind select to form you need to specify which formArray, formgroup and formControl you are binding in html.

In this case formControl is animalControl. but for you it will probably by labe or type. but you also need to specify which formGroup or FormArray they are in.

after setting all forms up. you can us *ngIf to check if formvalue is empty. If not you can show you next select. this Is all I can help.

nested custom FormArray component doesn't bind with child form with FormArrayName

you can also use formbuilder and add validators. you just need to do more reasearch on reactive forms for now.

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Vato, I have updated the code please look on it.

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.