Angular8 and formControlName with nested fields

54 views Asked by At

I spent many hours to solve this problem. My formGroup structure is:

 this.frameworkForm = this.formBuilder.group({
      id: [null],
      name: ['', Validators.required],
      active: [true],
      parsingRequired: [false],
      reviewRequired: [false],
      frameworkSortingType: {
        id: null,
        environmentalSortingType: '',
        socialSortingType: '',
        governanceSortingType: '',
      },
    });

In my template I want to get value from eg. environmentalSortingType:

     <div class="alphabetically">
                      <label class="control-label bold-label" for="reviewRequired">Alphabetically</label>
                      <div class="p-field-radiobutton">
                        <p-radioButton [name]="'environmental'" value="alphabetically"
                                       formControlName="frameworkSortingType.environmentalSortingType"
                        ></p-radioButton>

 <p-radioButton [name]="'environmental'" value="numerically"
                                   formControlName="frameworkSortingType.environmentalSortingType"
                    ></p-radioButton>
                      </div>

But that solution with . like formControlName="frameworkSortingType.environmentalSortingType" doesn't work. How to do that? I tried a lot of different ways... without success:(

UPDATE

I changed my code by adding nested formGroup but still I get the error: Cannot find control with unspecified name attribute (<div class="sorting" formGroupName="frameworkSortingType">)

 ngOnInit() {
    this.frameworkForm = this.formBuilder.group({
      id: [null],
      name: ['', Validators.required],
      active: [true],
      parsingRequired: [false],
      reviewRequired: [false],
      frameworkSortingType: this.formBuilder.group( {
        id: null,
        environmentalSortingType: '',
        socialSortingType: '',
        governanceSortingType: '',
      }),
    });

and my template:

  <div class="sorting" formGroupName="frameworkSortingType">
                <div class="alphabetically">
                  <label class="control-label bold-label" for="reviewRequired">Alphabetically</label>
                  <div class="p-field-radiobutton">
                    <p-radioButton [name]="'environmental'" value="alphabetically"
                                   formControlName="environmentalSortingType"
                    ></p-radioButton>
                  </div>
1

There are 1 answers

0
Derek Wang On BEST ANSWER

Based on this article, you can make frameworkSortingType as a new FormGroup and use this formGroup inside the main formGroup as follows.

enter image description here