Set a logic in the middle between p-chips and formcontrolname

1.1k Views Asked by At

Need help with p-chips and reactive forms: I have a structure in formgroup which is built like the database item.

valueSeperatedBySemi = "hi; hello; Whoop"

And I need to set it like this:

<p-chips formcontrolname="myFormCName" separator=";">

But it's not working since the p-chips needs an array. I cannot change valueSeperatedBySemi to an array.

How do I fix this?

1

There are 1 best solutions below

2
On BEST ANSWER

separator property is used to replace default enter key to add an item to the chips component. So it won't be useful in your case.

I think you should set an intermediate variable between the component and your data. Let's call it values: a string array.

<p-chips [(ngModel)]="values"></p-chips>

First, you need to transform your input data into a string array to fill your chips component:

this.valueSeperatedBySemi = "hi; hello; Whoop";
this.values = this.valueSeperatedBySemi.split("; ");

Then, if you want to get back your data formatted like in your database, you have to transform it back this way:

this.valueSeperatedBySemi = this.values.join("; ");

Of course, you can easily adapt this with formControl.

See demo