Skip to content

How can I get an array of numbers through a form in Angular?

I need the user to type an array of numbers through an input. But doing so just returns the array as a string to me. I wish I could somehow convert a string to an array of numbers, but I don’t know how.

Component.html:

<div class="d-flex justify-content-center mt-5">
  <div class="bg-white rounded-1 p-3" style="width: fit-content">
    <label for="array" class="form-label">INTRODUCE LA LISTA DE NUMEROS</label>
    <form [formGroup]="arrayForm" (ngSubmit)="enviarArray()">
      <input
        type="text"
        formControlName="userArray"
        id="array"
        class="form-control"
        aria-describedby="array"
        style="font-size: 35px"
      />
      <div class="text-center m-2">
        <button
          type="submit"
          class="btn btn-dark"
          style="width: 150px; height: 70px; font-size: 40px"
          [disabled]=""
        >
          Ordenar
        </button>
      </div>
    </form>
  </div>
</div>

Component.ts:

import { Component, OnInit } from '@angular/core';
import { ArrayService } from 'src/app/services/array.service';
import { Array } from 'src/app/models/Array';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [ArrayService],
})
export class HomeComponent implements OnInit {
  arrayForm: FormGroup;
  newArray: [] = []
  constructor(
    private arrayService: ArrayService,
    private formBuilder: FormBuilder
  ) {
    this.arrayForm = this.formBuilder.group({
      userArray: ['', Validators.required]
    })
  }
  
  ngOnInit(): void {}

  enviarArray(){
    console.log(this.arrayForm.value)
  }
}

Answer

1) You can use JSON.parse() to convert an array of string to an array of numbers

JSON.parse(text)

But be sure to handle exception. If the string that you pass is not valid JSON then it will throw SyntaxError

2) Then, you can check whether the parsed data is an array or not using Array.isArray

const input = document.querySelector("input");
const button = document.querySelector("button");

button.addEventListener("click", e => {
  const text = input.value;
  let arrayOfNumber;
  try {
    arrayOfNumber = JSON.parse(text);
    if (Array.isArray(arrayOfNumber)) {
      console.log("This is valid array: ")
      console.log(arrayOfNumber);
    }
  } catch (error) {
    console.log("Wrong Array");
  }
})
<input type="text" name="" id="">
<button>convert</button>