我正在创建嵌套的 formGroup 字段。以下是我的html
<form [formGroup]="userProfileForm" (ngSubmit)="bookUser()" class="form">
<!-- userName -->
<div class="form-group">
<label for="userName">Name:</label>
<input type="text" class="form-control" id="userName" formControlName="userName">
</div>
<!-- mobile -->
<div class="form-group">
<label for="mobileNumber">Mobile:</label>
<input type="text" class="form-control" id="mobileNumber" formControlName="mobileNumber">
</div>
<!-- emailId -->
<div class="form-group">
<label for="emailId">Email id:</label>
<input type="text" class="form-control" id="emailId" formControlName="emailId">
</div>
<!-- password -->
<div class="form-group">
<label for="password">Password:</label>
<input type="text" class="form-control" id="password" formControlName="password">
</div>
<!-- address -->
<div class="form-group">
<div formGroupName="address">
<label for="city">City:</label>
<input type="text" class="form-control" id="city" formControlname="city">
<label for="state">State:</label>
<input type="text" class="form-control" id="state" formControlname="state">
<label for="zipCode">Zip Code:</label>
<input type="text" class="form-control" id="zipCode" formControlname="zipCode">
</div>
</div>
<button type="submit" class="btn btn-primary">Create Profile</button>
</form>
下面是我正在使用的打字稿......
ngOnInit() {
this.userProfileForm=this.formBuilder.group({
userName:['', Validators.required],
mobileNumber:['', Validators.required],
emailId:['', Validators.required],
password:['', Validators.required],
address: this.formBuilder.group({
city:['', Validators.required],
state:['', Validators.required],
zipCode:['', Validators.required]
})
});
}
当我尝试在 html 中打印它时,我没有收到city
子 formGroup 的 formControl。我尝试以不同的方式访问该值,例如:
(<FormGroup>this.userProfileForm.get('address')).get('city').value;
但
this.city=this.userProfileForm['controls'].address['controls'].city.value
我仍然无法让城市字段在 html 中显示。我也用过this.city=this.userProfileForm['controls'].address['controls'].city.valid
,它总是返回false。
我还创建了 2 个模型类: UserProfile
import { Address } from "./address";
export class UserProfile{
userName:string;
emailId:string;
password:string;
mobileNumber:string;
address:Address;
}
地址
export class Address{
city:string;
state:string;
zipCode:string;
}
如何访问嵌套的 formGroup 值?我在这里做错了什么?