I am working on a form in Angular 14. I run into a problem while using deeply nested form groups. (It is not a choice to do so, it is a necessity).
In form.component.ts
I have:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FormService } from '../services/form.service';
@Component({
selector: 'my-app',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent {
public accountTypes!: any;
public selectedAccountType: any;
public form: FormGroup = new FormGroup({
first_name: new FormControl('', Validators.required),
last_name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
phone: new FormControl('', Validators.required),
accountEssentials: new FormGroup({
accountInfo: new FormGroup({
account_type: new FormControl(''),
}),
}),
});
constructor(private formService: FormService) {}
ngOnInit(): void {
this.getAccountTypes();
}
public getAccountTypes() {
this.formService.getAccountTypes().subscribe((response) => {
this.accountTypes = response;
this.form.controls['accountEssentials.accountInfo'].patchValue({
account_type: this.accountTypes[0].value,
});
});
}
public sendFormData() {
console.log(this.form);
}
}
The form's template:
<form [formGroup]="form">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label >Fast name:</mat-label>
<input matInput formControlName="first_name" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label >Last name:</mat-label>
<input matInput formControlName="last_name" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label >Email:</mat-label>
<input matInput formControlName="email" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label >Phone:</mat-label>
<input matInput formControlName="phone" />
</mat-form-field>
<div formGroupName="accountEssentials">
<div formGroupName="accountInfo">
<mat-radio-group
formControlName="account_type"
[(ngModel)]="this.selectedAccountType"
>
<mat-radio-button
*ngFor="let accountType of accountTypes"
[value]="accountType.value"
>
<span >{{ accountType.label }}</span>
</mat-radio-button>
</mat-radio-group>
</div>
</div>
</form>
See this Stackblitz.
The problem
The patchValue
method does not work on the account_type
form control that I try to access with accountEssentials.accountInfo
.
this.form.controls['accountEssentials.accountInfo'].patchValue({
account_type: this.accountTypes[0].value,
});
What is the most reliable way to achieve the desired result?
CodePudding user response:
I think you're looking for FormGroup.get()
which allows you to call patchValue
this.form.get('accountEssentials.accountInfo')?.patchValue(...)