我想创建一个位置对象,里面有两个参数。 我可以使用FormGroup创建一个数组或字符串,但我不知道如何创建一个内部有两个参数的Object。这是我用于的代码:
bucketForm: FormGroup; // at the top of the class component
ngOnInit() {
this.initForm();
}
private initForm() {
let bucketName = '';
let bucketLocation = {};
let bucketObjects = new FormArray([]);
this.bucketForm = new FormGroup({
'name': new FormControl(bucketName, Validators.required),
'location': // Here I want to create Location Object with two parameters {id: 'Some random number', name: 'New York'},
'bucketObjects': bucketObjects
});
console.log(this.bucketForm);
}
我得到组件的值格式.html文件,这里有一个简单的表单,它是我正在使用的完整代码:
<form [formGroup]="bucketForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="col-md-6">
<label for="name">Bucket Name*</label>
<input
type="text"
class="form-control"
id="name"
formControlName="name">
</div>
<div class="col-md-6">
<label for="bucketLocation">Bucket Location*</label>
<select
class="custom-select d-block w-100"
id="bucketLocation"
formControlName="location">
<option
*ngFor="let locationEl of locations" [value]="locationEl.name">{{ locationEl.name }}
</option>
</select>
</div>
</div>
<hr>
<button
type="submit"
class="btn btn-primary"
[disabled]="!bucketForm.valid">Create Bucket
</button>
<button class="btn btn-danger">Cancel</button>
</form>
这是我的桶模型,我使用的是数组:
Bucket {
id: "BucketExample", // string
name: "BucketExample", // string
location: Location, // object { id: string, name: string }
bucketObjects: Array(0)
}
屏幕截图:https://d2ffutrenqvap3.cloudfront.net/items/071z2l0Y3N3a2P25463O/print-scr-bucket.jpg
答案 0 :(得分:0)
您正在尝试将对象设置为表单的某个属性的值。
要将对象作为属性,您必须使用FormGroup
而不是FormControl
。
您可以在另一个FormGroup
内拥有FormGroup
,因此bucketForm
应为
this.bucketForm = new FormGroup({
'name': new FormControl(bucketName, Validators.required),
'location': new FormGroup({
id: new FormControl(Math.random()),
name: new FormControl('')
}),
'bucketObjects': bucketObjects
});
要将select
控件的值设置为对象而不是原始值,您必须使用ngValue
因为我们要直接设置一个对象,
提供表单控件对象作为输入,而不是提供formControlName
属性。
i,e 而不是
formControlName="location"
使用
[formControl]="bucketForm.get('location')"
所以你的HTML看起来应该是这样的,
<select class="custom-select d-block w-100" id="bucketLocation" [formControl]="bucketForm.get('location')">
<option
*ngFor="let locationEl of locations" [ngValue]="locationEl">{{ locationEl.name }}
</option>
</select>
答案 1 :(得分:0)
以下是解决方案:
HTML文件:
<select class="custom-select d-block w-100"
id="bucketLocation"
formControlName="location"
ngModel>
<option value="" disabled>Choose...</option>
<option
*ngFor="let locationEl of locations" [ngValue]="locationEl">{{ locationEl.name }}
</option>
</select>
TypeScript文件:
private initForm() {
let bucketName = '';
let bucketLocation = {};
let bucketObjects = new FormArray([]);
this.bucketForm = new FormGroup({
'name': new FormControl(bucketName, Validators.required),
'location': new FormControl(bucketLocation, Validators.required),
'bucketObjects': bucketObjects
});
}
我从这里找到了解决方案: Angular API doc
还要感谢@ cyberpirate92