Home > Software design >  Angular: Access formcontrol by ID
Angular: Access formcontrol by ID

Time:12-14

I would like to access my formcontrols by IDs and not by names like this:

profileForm = this.fb.group({
    account1: [true, alias:1]
    account2: [true, alias:2]
});

this.profileForm.get(1)...

My issue:

profileForm = this.fb.group({
    notification: [],
    user: this.fb.group({
      accounts: this.fb.group({})
    })
});

(this.profileForm.get('user.accounts')as FormGroup).addControl('accountname.withDot', this.fb.control(false));

If I want to change value of 'accountname.withDot' I do:

(this.profileForm.get('user.accounts.accountname.withDot') as FormGroup).patchValue(true);

This way I get this error:

enter image description here

Thanks in advance for any help.

CodePudding user response:

You can find two solutions to your problems, do let me know if any doubts.

Best Method:

    (
      this.profileForm.get(['user', 'accounts', 'accountname.withDot']) as FormGroup
    ).patchValue(true as any);

Reference link

First method: replace dot with underscore.

Second method: use the below helper method.

ts

import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  FormControl,
  Validators,
  FormArray,
  FormBuilder,
} from '@angular/forms';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  profileForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.profileForm = this.fb.group({
      notification: [],
      user: this.fb.group({
        accounts: this.fb.group({}),
      }),
    });
    // solution 1 - use underscore instead!
    (this.profileForm.get('user.accounts') as FormGroup).addControl(
      'accountname_withDot',
      this.fb.control(false)
    );
    (
      this.profileForm.get('user.accounts.accountname_withDot') as FormGroup
    ).patchValue(true as any);

    // solution 2 use this helper function!
    // reset form
    this.profileForm = this.fb.group({
      notification: [],
      user: this.fb.group({
        accounts: this.fb.group({}),
      }),
    });
    (this.profileForm.get('user.accounts') as FormGroup).addControl(
      'accountname.withDot',
      this.fb.control(false)
    );
    // below code will result in error
    // (
    //   this.profileForm.get('user.accounts.accountname.withDot') as FormGroup
    // ).patchValue(true as any);
    // below code will not result in error
    console.log(
      this.drilldownControls(this.profileForm, [
        'user',
        'accounts',
        'accountname.withDot',
      ])
    );
    this.drilldownControls(this.profileForm, [
      'user',
      'accounts',
      'accountname.withDot',
    ]).patchValue(true as any);
  }

  drilldownControls(form: FormGroup | FormControl, controlList: Array<string>) {
    let item: FormControl = <FormControl>form.get([controlList[0]]);
    if (item) {
      controlList.shift();
      if (controlList.length) {
        item = this.drilldownControls(item, controlList);
      }
    }
    return item;
  }
}

// angular form is group of controls

forked stackblitz

  • Related