Angular响应式表单嵌套取值异常:address.city正常floor_installer.id报错
Hey there! Let's break down why address.city works perfectly for getting values, but floor_installer.id throws that frustrating TypeError. The key lies in how you've structured your nested form controls.
1. The Core Difference Between address and floor_installer
Let’s look at your FormBuilder setup:
For
address, you created a properFormGroupusingthis.fb.group():const addressGroup = this.fb.group({ street: '', city: '', postal_code: '', province: '', });Angular recognizes this as a nested form group, so you can use dot notation (
address.city) with theget()method to directly access child controls.For
floor_installer, you just assigned a plain JavaScript object without wrapping it in aFormGroup:floor_installer: { id: '', name: '', },To Angular, this is just a single
FormControlwhose value happens to be an object. It doesn’t treatidornameas separate form controls—so there’s no "child control" to access withfloor_installer.id.
2. Why the Error Occurs
When you run this.addEventForm.get('floor_installer.id'):
- Angular first finds the
floor_installercontrol (which exists, but it’s a FormControl, not a FormGroup). - It then tries to look for an
idcontrol insidefloor_installer—but sincefloor_installerisn’t a FormGroup, there’s no such child control to find. - The
get()method returnsnull, and trying to access.valueonnullthrows theTypeErroryou’re seeing.
3. Fixes to Access floor_installer.id
You have two solid options here:
Option 1: Grab the value from the FormControl directly
Since floor_installer is a single FormControl with an object as its value, retrieve the whole value first, then pick out the id:
const floorInstallerId = this.addEventForm.get('floor_installer').value.id;
Option 2: Convert floor_installer to a FormGroup
If you want to use the same dot notation as address.city, wrap floor_installer in a FormGroup just like you did with address:
// Create a FormGroup for floor_installer const floorInstallerGroup = this.fb.group({ id: '', name: '' }); // Update your main form this.addEventForm = this.fb.group({ // ... other controls ... floor_installer: floorInstallerGroup, address: addressGroup, // ... other controls ... });
Now you can safely use:
const floorInstallerId = this.addEventForm.get('floor_installer.id').value;
内容的提问来源于stack exchange,提问作者Tolgon

