How can I bind form data to an array in Angular?

import { Component, OnInit } from '@angular/core';
import { Senderv3 } from 'app/models/codec/senderv3';
import { CustomerInfoService } from '../../../services/customer-info.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-senderv3',
  templateUrl: './senderv3.component.html',
  styleUrls: ['./senderv3.component.scss']
})
export class Senderv3Component implements OnInit {

  VirtualMsisdn = new FormControl('', Validators.required);
  OperatorVariantId = new FormControl('', Validators.required);
  SmsHeader = new FormControl('', Validators.required);
  ServiceCode = new FormControl('', Validators.required);
  form: FormGroup;

  senders: Senderv3[] = [ { VirtualMsisdn: this.VirtualMsisdn.value, OperatorVariantId: this.OperatorVariantId.value, 
    SmsHeader: this.SmsHeader.value, ServiceCode: this.ServiceCode.value } ] as Senderv3[];

  constructor(private customerInfoService: CustomerInfoService, private router: Router, private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      VirtualMsisdn: this.VirtualMsisdn,
      OperatorVariantId: this.OperatorVariantId,
      SmsHeader: this.SmsHeader,
      ServiceCode: this.ServiceCode,
    });
  }

  insertSenderv3() {
    this.customerInfoService.insertSendersv3(this.senders).subscribe();  
  }


}

<button mat-raised-button (click)="insertSenderv3()" type="button" class="btn btn-success">Save</button>

Why is the parameter object for insertSendersv3(this.senders) empty? (OperatorVariantId:"" ServiceCode:"" SmsHeader:"" VirtualMsisdn:"")

Check out the screenshots below:

View picture 1 View picture 2

Your assistance on this matter would be greatly appreciated.

Thank you!

Answer №1

Instead of manually creating controls with

new FormControl('',Validators.required)
when using the formBuilder, you can simplify your form creation process.

For a basic form, consider implementing it like this:

  form: FormGroup;

  senders: Senderv3[] = [];

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      VirtualMsisdn: ['' ,  Validators.required],
      OperatorVariantId: ['' ,  Validators.required],
      SmsHeader: ['' ,  Validators.required],
      ServiceCode: ['' ,  Validators.required],
    });
  }

  insertSenderv3() {
    this.senders.push(this.form.value);
    console.log(this.senders)
  }

By clicking the button, the this.form.value will hold values of type Senderv3.

An example demonstrating this setup is available on stackBlitz here: https://stackblitz.com/edit/angular-kxfynp

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

Dealing with form errors - Using Node.js and Express Framework

Is there a way to handle errors that occur when dealing with null form inputs or unavailable cities from the weather api service? Sometimes, when an empty query or a misspelled city is inputted, the server returns errors and halts operation. app.get("/", ...

Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example: ['foo', 'bar'] After trying different approaches, the closest solution I found looks like this: Yup.array() .of(Yup.mixed().oneOf(['foo&a ...

Angular is disregarding certain JSON fields when creating objects

My goal is to fetch data from the wagtail API, but it returns the JSON in a complex format. { "id": 3, "meta": { "type": "home.HomePage", "detail_url": "http://localhost:8000/api/v1/pages/3/" }, "parent": null, "title": ...

Loop through an array of names in a post input field

There is an array in a while loop, please check the code below: <?php $addItemSql = "SELECT * from tbl_invoice_services where col_cust_id='$getID' ORDER BY col_service_id"; $addItemResult = mysqli_query($db, $addItemSql); while ($addItemRow ...

What is the process of importing an npm module into an Angular application?

While searching for a solution, I stumbled upon this npm package that allows us to group arrays according to our needs. I want to integrate this package into my Angular application for grouping arrays. What is the correct way to import this package into ...

Executing PHP script using AJAX displays an empty outcome

I want to execute a php script through ajax after submitting a form. Here is the form <form id="form" class="form"> <input id="email" type="email" required name="email" placeholder="Email" onchange="myUpdateFunction()" value=""> <te ...

Express.js and Node.js middleware for validating all form submissions

Are there any middleware functions available for validating all form entries in node.js and express.js? I am interested in checking for special characters without having to validate each individual form field every time. Thank you! ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

Sending selected IDs from the JSON data

In my project, there is a JSON file named "workers" which contains information about all the workers. I have created a select component to display the names of the workers like this: https://i.sstatic.net/0Glyf.png Currently, I am selecting some workers ...

The form's action redirects to http//localhost/xampp instead of the intended destination

I am a beginner in CodeIgniter and I have set up a homepage with a form controller. When I click submit on the homepage, I want it to redirect to the signup function in the form controller. However, it is redirecting to http//localhost//xampp This is the ...

How does TypeScript interpret the data type 'a' | 'b' as a string?

As a beginner in TypeScript, React, and English, I apologize for any confusion. I have written a function like this: interface ObjectAttrUniqueState { editVisible: boolean; currentId: number; selectedUnique: number[]; name: string; desc: string; ...

Understanding and working with nested arrays in PHP

Upon receiving JSON data, the format appears as follows: { "destination_addresses": [ "67-89 Pacific St, Brooklyn, NY 11201, USA" ], "origin_addresses": [ "566 Vermont St, Brooklyn, NY 11207, USA" ], "rows": [ { "elements": [ ...

Structs providing aliases for arrays

In my current reading of ISO/IEC 9899:TC2, I have reached paragraph 7 of section 6.5. It allows lvalue access to an object through: an aggregate or union type that includes one of the types mentioned earlier among its members (including, recursively, ...

Can this be executed in PHP?

Can this code snippet work in PHP? foreach (function() { return ['key' => 'Value']; } as $key => $val){ $new_array = array('Key' => $key, 'Value' => $val); } I am interested in mo ...

Python: Matching one value against multiple values from arrays

I have a code snippet that goes like this: import requests import re import mechanize import urllib import json htmltext = urllib.urlopen("https://www.binance.com/api/v1/klines?symbol=BCDBTC&interval=4h") data = json.load(htmltext) current_price= d ...

Tips for arranging columns and rows in a mat-dialog box

In my Angular project, I am working on a mat dialog box and trying to achieve a layout with 1 row at the top and 3 rows at the bottom, similar to the image below. However, I am facing issues in making it work properly. Additionally, I want to hide the hori ...

Substitute values smaller than a certain threshold with zeros in a NumPy array

In my Python script, I am working with a NxT Numpy array that contains N time series data points (random walk) of length T. My goal is to identify any values in a specific series (row) that are below a certain threshold, let's say 8000, and replace th ...

Verify the presence of a specific value within an array of objects in JavaScript that was retrieved from an AJAX response, and then

I am encountering an issue with the code below where I am unable to filter entry.AllLinks. The code snippet is shown here: $.ajax({ url: url, type: "get", headers: {"Accept": "application/json;odata=verbose"}, success: function (data) { ...

Show details when clicked with various elements

I have a dilemma with my Angular version 7 project. In a div, I have placed 6 buttons in 2 columns and I want to show a description of one button only when it is clicked. Currently, the description for all buttons displays at once upon clicking any button. ...

Converting an array of arrays into an object with an index signature: A step-by-step guide

I find myself facing a challenge where I have two types, B and A, along with an array called "a". My objective is to convert this array into type B. Type A = Array<[string, number, string]>; Type B = { [name: string]: { name: ...