Issue
I have an angular app and in my form, I have a multi-select. Multiselect value will be stored in an array, therefore I am using angular formsArray.
in my app.component.ts:
{{testForm.value|json}}
<form nz-form [formGroup]="testForm">
<div>
<p>Title</p>
<nz-input formControlName="title"></nz-input>
</div>
<div>
<p>Items</p>
<nz-select
[nzMode]="'multiple'"
[nzPlaceHolder]="'Choose items'"
formArrayName="items"
[nzNotFoundContent]="'Item not found'"
>
<nz-option
*ngFor="let item of items"
[nzLabel]="item.title"
[nzValue]="item.id"
>
</nz-option>
</nz-select>
</div>
</form>
and inside the .ts file:
export class AppComponent {
testForm: FormGroup;
items = [
{
title: "Item 1",
id: 1,
},
{
title: "Item 2",
id: 2,
},
];
constructor(private fb: FormBuilder) {
this.testForm = this.fb.group({
title: "",
items: this.fb.array([]),
});
}
}
However, the problem is that, even though I selected the multiple items, but I am getting an empty array like that:
{ "title": "test", "items": [] }
items, attribute is not filling up with the value from nz-select. I have created an app with this example. Here is the link.
Solution
Having multiple values does not mean you have to use formArray. Just change in your html formArrayName="items" to formControlName="items"
<nz-select
[nzMode]="'multiple'"
[nzPlaceHolder]="'Choose items'"
formControlName="items"
[nzNotFoundContent]="'Item not found'"
>
<nz-option
*ngFor="let item of items"
[nzLabel]="item.title"
[nzValue]="item.id"
>
</nz-option>
</nz-select>
And your ts file have to look like
this.testForm = this.fb.group({
title: [''],
items: [[]],
});
Answered By - FolabiAhn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.