How do I build the FormBuilder correctly on a select multiple? It only works without being multiple.
I tried using FormArray, FormGroupName in HTML, however, all returning errors. And the examples I encounter are always non-tagged <select multiple>
.
Could someone guide me? Thanks.
.TS
this.detailFormGroup = this.fb.group({
"id": [this.item.id],
"name": [this.item.name, [Validators.required]],
"categories": this.item.categories
});
.HTML
<form [formGroup]="detailFormGroup">
<div>
<input type="text" formControlName="name" />
</div>
<div>
<select formControlName="categories" multiple>
<option *ngFor="let item of categories" [value]="item.id">{{ item.categoryName }}</option>
</select>
</div>
</form>
What I need is that when I get the detailFormGroup.value I receive the object:
{
id: 1,
name: "name 1",
categories: [
{
id: 5,
categoryName: "name 5"
},
{
id: 10,
categoryName: "name 10"
}
]
}
And of course, when I set the item object, the HTML controls are also selected with their items.
I'm getting wrong like this:
{
id: 1,
name: "name 1",
categories: [ 5, 10 ]
}
You are getting an array of selected values. And in your HTML we can see option [value]="item.id"
.
Just change this to option [value]="item"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.