Extracting comma-separated values from an input in Angular PrimeNG and saving them as an array

Currently, I am experimenting with the comma-separated chips component from PrimeNG as an input field within a form. My goal is to extract the values entered into the input field and store them as individual values in an array. Despite my attempts to troubleshoot by replicating the issue on StackBlitz [link provided below], I have encountered difficulties converting the values into a string for manipulation. It seems that this challenge may stem from incorrect usage of certain elements and inadequate binding. Any insights or suggestions would be greatly appreciated.

Check out the demo on StackBlitz

Answer №1

Below are the issues identified in your code:

  1. app.component.hmtl: It is unnecessary to use [(ngModel)] alongside formControlName. Both serve the same purpose, so choose one depending on your requirements. If your component is part of a reactive form, it is recommended to use formControlName and bind it to a FormControl within the FormGroup defined in your .ts file.
  2. app.component.ts: Remember to create a FormControl with the same name as specified in the .html file within your FormGroup to establish the binding properly. Access the control's value 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]);
      }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it necessary for me to employ a type assertion when the type should be evident logically?

I'm facing a situation where I can logically determine the type of an object, but I end up having to use type assertion and create additional dummy variables to access type-specific properties correctly. Is there a more efficient approach to handle th ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

The service subscription in the ngOnInit lifecycle hook is only invoked once and does not remain populated when the route changes

I need some clarification. The Angular app I'm working on is successfully populating data to the view, but when navigating from one component to another, the ngOnInit lifecycle hook doesn't seem to be invoked, leaving the list on the view empty. ...

Error in Protractor Typescript: The 'By' type does not share any properties with the 'Locator' type

https://i.stack.imgur.com/8j2PR.png All the different versions Error. Protractor version : 5.2.0 npm : 3.10.10 node :6.9.5 typescript :2.6.0 The 'By' type does not share any properties with the 'Locator' type What is the solution to ...

Displaying only the radio button without any additional elements, the Ionic 2 radio button (<ion-radio>) offers a

Looking for some guidance on implementing a list with radio buttons using the ion-list and ion-radio directives. The code provided should be clear, but please feel free to ask for more details if needed. I'm still new to Ionic and may be making some ...

When using @testing-library/react (rtl), the 'waitFor' function achieves success even without the need for the 'await' keyword

waitFor() is causing my test to fail while waitFor() (without await) makes it pass. The official documentation states: Async methods return a Promise, so you must always use await or .then(done) when calling them. (https://testing-library.com/docs/guide ...

Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. Howe ...

Duplicated RxJs in Angular 5 with Webpack 4 and Rxjs 5 DllPlugin - a common issue plaguing

My current configuration includes: "webpack": "4.12.0", "rxjs": "5.5.9", "@angular" : "5.2.11" and I am bundling libraries with the DDL Plugin. { entry: {"rxjs_5_5_9": [ "rxjs ], "angular_5_2_11": [ "@angular/common", ...

What are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

Phaser.js troubleshooting: Overcoming TypeScript errors

I encountered two persistent errors that I have been unable to resolve. While the application runs smoothly in Vite, it fails to transpile due to the mentioned errors outlined below: import Phaser from "phaser"; export default class GameScene ex ...

Guide on implementing ng-bootstrap in AngularJS 2 (utilizing angular-cli version 1b15)

I've been attempting to incorporate ng-bootstrap into my Angular 2 project by following the guidelines provided on the official ng-bootstrap website. Here's what I have done so far: npm install <a href="/cdn-cgi/l/email-protection" class="_ ...

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Encountering an issue while trying to load a file from an API due to difficulties in parsing it to

When trying to load an xlsx file from an API, I encountered an error because Angular automatically tries to parse the body as JSON. To resolve this issue, I found that specifying the response type directly in the request works: this.http.get(this.url + " ...

An unhandled promise rejection occurred because no routes could be found to match. URL Segment:

I'm facing an issue with my application where it doesn't recognize the route even though I have defined and imported it in app.module. Whenever I try to redirect to a specific route upon data retrieval, I encounter this exception: onSubmit(){ ...

The issue with Angular version 15 p-dialogue not displaying HTML content when using a component selector

In my Angular application, I have an issue with rendering a component called urc.component from a different module (variance.module) inside another module (nursing-audit.module). The p-dialogue is opening and displaying the header correctly, but the urc.co ...

Encountering an unexpected token error while trying to compile a Typescript file to Javascript, even though it had previously worked

In my Typescript project, I usually run it using "ts-node". $ ts-node .\src\index.ts it works =) However, I wanted to compile it to Javascript, so I tried the following: $ tsc $ node .\src\index.js Unfortunately, I encountered the f ...

Selecting an option with a specific index in Angular 2 RC2

I have encountered a situation where the select options are non-unique, with the same value representing different things. This is how our data is structured and I need to work within those constraints. <select id="mySelect"> <option value = "1 ...

The 'string' data type cannot be assigned

Let me share how I define and utilize my font sizes in my custom React app: FontSizes.ts const fontSizes = { xs: 'xs', sm: 'sm', base: 'base', lg: 'lg', xl: 'xl' ...

Query Parameter Matching in Typescript: Retrieve and output all query parameter values that correspond to a specific parameter

Is there a way to extract all value for a specific query parameter from an URL? For example, if we have a string like ?code1=AF&code1=AE&code1=GE&code3=FW Can we search this string for all values associated with the parameter code1? So, in ...

Ensuring that the containing element always spans the full height of the page, regardless of the varying number of dynamic child elements

I am struggling to make a container div expand dynamically in height so that it always matches the height of its content. The overall structure is search.html <div class="outer-container"> <div class="inner-container"> ...