我想创建一个包含两个参数的位置对象。我可以用 FormGroup 创建一个数组或字符串,但我不知道如何创建一个里面有两个参数的对象。这是我使用的代码:
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