Ensure Angular Reactive Forms do not include empty fields when submitting the form

Is there a way to retrieve only the fields with values entered by the user from a form and exclude empty fields in the resulting JSON object? Currently, the JSON object still includes empty quotation marks for empty inputs. Thank you!

Current:

{ "user": "", "directory": "documents", "filename": [ "a", "", "" ] }

Desired Output:

{ "directory": "documents", "filename": [ "a" ] }

Answer №1

In the scenario where form controls are not given an empty value, they will automatically default to null.

If you are constructing your form in the following manner:

import { Component } from '@angular/core';
import { FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private fb: FormBuilder) {}

  userForm = this.fb.group({
    user: [],
    directory: [],
    filename: this.fb.array([])
  });

  addFile() {
    (<FormArray>this.userForm.get('filename')).push(this.fb.control(null));
  }

  get files() {
    return (<FormArray>this.userForm.get('filename')).controls;
  }

  onSubmit() {
    console.log(this.userForm.value);
  }

}

Any unfilled fields in the form would be interpreted as null. To exclude these from the value, consider the following approach:

onSubmit() {
  let formValue = { ...this.userForm.value };

  for (let prop in formValue) {
    if (!formValue[prop]) {
      delete formValue[prop];
    }

    if (Array.isArray(formValue[prop])) {
      let resultArray = formValue[prop].filter(item => item);
      if (resultArray.length > 0) {
        formValue[prop] = resultArray;
      } else {
        delete formValue[prop];
      }
    }
  }
  console.log(formValue);
}

For reference, here is a Sample StackBlitz of this implementation.

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

Creating an If statement tailored for a particular image source: a step-by-step guide

In the program I am running in Dreamweaver, there is a specific line of code that looks like this: function go() { if((document.test.test1.src == document.test.test2.src && document.test.test2.src == document.test.test3.src )) ...... ...... ..... ...

Exploring Particles with three.js

Could you please help me understand why there are no particles visible in this code snippet? I followed a tutorial and it all seems correct. (function() { var camera, scene, renderer; init(); animate(); function init() { scene = new THREE.Scene(); ...

Combining Angular and Material Design: matdrawer and mattoolbar creating an overlapping effect

I'm currently facing a challenge in trying to construct a drawer that includes a mattoolbar, intended to overlap the primary toolbar of my application. Despite my efforts, I have been unable to rearrange the drawer higher up in the component hierarch ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Manipulate the text within a swf file using jQuery

Looking for a solution to target links inside a SWF file connected to XML without access to the .fla or .swf files. Is there a way to achieve this using jQuery or Javascript? Any help is appreciated. ...

When executing code in React JS, I encountered no errors, but the output did not match my expectations

I am facing a challenge with running the Hello World program in React JS using webpack. Attached below is the project structure for reference: https://i.stack.imgur.com/tQXeK.png Upon executing the npm run dev command in the CLI, the browser launches bu ...

How to shuffle the elements of an array saved in a JSON file using discord.js

I've been working on a Discord bot as a way to learn more about Javascript. While creating a command that pulls random quotes from an array stored in a separate JSON file, I encountered an issue that has me stumped. var config = require("./settings.j ...

Plunker fails to run simple AngularJS demo

I'm having trouble figuring out why this basic example isn't functioning as expected on Plunker. http://plnkr.co/edit/EfNxzzQhAb8xAcFZGKm3?p=preview var app = angular.module("App",[]); var Controller = function($scope){ $scope.message ="Hel ...

What is the process for listening to custom events in Angular 4 components that have been loaded using routing?

In the app.component.html file <li routerLinkActive="active current"> <a [routerLink]="['/stats']"> Cluster stats </a> </li> When we route to the DisplayAllStatsComponent, how can we ...

NodeJs ERROR: Module not found

When trying to launch an instance running ubuntu with express, I encountered a module not found error that does not occur on my Windows machine. Error Message: node:internal/modules/cjs/loader:1085 throw err; ^ Error: Cannot find module './src/c ...

The concept of setTimeout and how it affects binding in JavaScript

I have limited experience with jquery, mainly using it for toggling classes. However, I will do my best to explain my issue clearly. I have three div elements and when one is clicked, the other two should rotate 90 degrees and then collapse to a height of ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

My table elements are automatically being populated with <tr> elements thanks to Javascript

Upon viewing the screenshot: https://i.sstatic.net/Pwv2v.png it is evident that each element is placed within its own tr. My preference is to have each element contained in a td and then wrap everything within a single tr. Here is the updated HTML stru ...

JavaScript Popup prompting user on page load with option to redirect to another page upon clicking

Can a JavaScript prompt box be created that redirects to a site when the user selects "yes" or "ok," but does nothing if "no" is selected? Also, can this prompt appear on page load? Thank you! UPDATE: Answer provided below. It turns out it's simpler ...

Error message: "AngularJS encountered a $injector:modulerr error in Internet Explorer 11."

I've successfully created an AngularJS App that functions properly on most browsers like Firefox, Opera, Safari, Edge, and Chrome. However, there seems to be a compatibility issue with IE 11. When attempting to open the app in IE 11, the following er ...

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...

Set a restriction on the Bootstrap DatePicker to only show dates within a

My application features StartDate and EndDate datepickers, and I need to implement a 30-day limit on the selection range to prevent performance issues caused by loading too much data. I'm looking for a functionality where if the user picks today as t ...

Is there a way to automatically initiate the download of a file (such as a PDF) when a webpage loads?

Currently, my objective is to have a form on a webpage that, once filled out by a user, redirects them to a thank you page where a message of gratitude is displayed. What I aim to accomplish is for a PDF file to automatically start downloading as soon as t ...

Error encountered: JSHint is flagging issues with setting a background gradient using

I have been experimenting with animating a background gradient using jQuery, and here is the code snippet I am working with: this.$next.css('line-indent', 0).animate({ 'line-indent': 100 }, { "duration": 750, "step": functi ...

Prevent Angular Router from Initiating NavigationStart

Can the NavigationStart event be prevented in Angular? I am attempting to display a customized confirmation modal when the user attempts to switch routes. constructor(private router: Router) { if(val instanceof NavigationStart){ //Display th ...