Angular 5中如何通过FormGroup创建含双参数的Location对象
创建包含多参数对象的FormGroup控件
要创建包含两个参数的Location对象类型控件,你需要使用嵌套FormGroup来实现——把Location的每个属性作为嵌套FormGroup中的独立FormControl,就像你用FormGroup创建主表单那样。
下面是修改后的完整代码示例,假设你的Location对象包含latitude和longitude两个参数(你可以根据实际属性名替换):
bucketForm: FormGroup; // 组件类顶部定义 ngOnInit() { this.initForm(); } private initForm() { let bucketName = ''; // 用嵌套FormGroup定义Location对象的两个参数 let bucketLocation = new FormGroup({ 'latitude': new FormControl(null, Validators.required), // 可根据需求添加验证器 'longitude': new FormControl(null, Validators.required) }); let bucketObjects = new FormArray([]); this.bucketForm = new FormGroup({ 'name': new FormControl(bucketName, Validators.required), // 保留你原有的验证规则 'location': bucketLocation // 将嵌套的FormGroup加入主表单 }); }
额外实用说明:
- 如果需要给Location的参数设置初始值,直接在FormControl中传入对应值即可,比如
new FormControl(39.9, Validators.required) - 访问嵌套控件时,可使用路径语法:
this.bucketForm.get('location.latitude');也可以先获取整个Location组再访问具体控件:const locationGroup = this.bucketForm.get('location') as FormGroup; const longitudeControl = locationGroup.get('longitude'); - 在模板中绑定嵌套控件时,需要在包裹输入框的元素上添加
formGroupName="location",然后用formControlName绑定具体属性,比如:<div formGroupName="location"> <input type="number" formControlName="latitude" placeholder="纬度"> <input type="number" formControlName="longitude" placeholder="经度"> </div>
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

