0
votes

I am trying to use comma seperated chips component from prime ng as an input field in the form. I want to be able to extract the values entered in the input field and store them as separate values in an array. I have tried to recreate the problem in stackblitz [link below] nut am not able to convert the values to a string for manipulation, this may be due to improper use of and not binding properly. Any input appreciated.

https://stackblitz.com/edit/primeng-chips-demo-4a6hfi?file=src%2Fapp%2Fapp.component.ts

1

1 Answers

1
votes

This are the problems with your code:

  1. app.component.hmtl: You dont need to use [(ngModel)] when using formControlName. Both things do the same thing, so you should only use of them, depending on what you want to do. If your component is defined inside of a reactive form, then the logical thing is to use formControlName and bind it to a FormControl of the FormGroup in your .ts file.
  2. app.component.ts: As I said, you have to create a FormControl inside your FormGroup, with the same name that you defined in the .html file, to bind it to the component. Then you access the value of the control through the FormGroup.

app.component.html:

<form
[formGroup]="aForm"
(ngSubmit)="onSubmit()">
  <label>Comma Separator</label>
  <p-chips 
  formControlName="valuesArray"
  separator=","></p-chips>
  <button type="submit">Submit</button>
</form>

app.component.ts:

import { Component } from '@angular/core';
import {MenuItem} from 'primeng/api';
import {FormBuilder, FormControl, FormGroup} from '@angular/forms'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

    valuesArray: [];
    
  aForm: FormGroup;

  constructor(
    private _formBuilder: FormBuilder
  ){
    this.aForm = new FormGroup({
      ValuesArray: new FormControl('')
    })
  }


    onSubmit() {
      let stringIn = this.aForm.controls.ValuesArray.value;
      stringIn = stringIn.split(',');
      for (let i =0; i < stringIn.length; i++){
        console.log(stringIn[i]);
      }
    }
}