Angular Reactive Forms - Adding Values Dynamically

I have encountered an issue while working with a reactive form. I am able to append text or files from the form in order to make an http post request successfully. However, I am unsure about how to properly append values like dates, booleans, or arrays.

addPost(postAdded: Post, image: File) {
    const postData = new FormData();
    postData.append("title", postAdded.title); // string
    postAdded.append("startDate", postAdded.startDate); // date
    postAdded.append("private", postAdded.private); // boolean
    postAdded.append("image", image, postAdded.title); // file
    this.http
      .post<{ postId: string }>(
        "http://localhost:3000/api/posts",
        postAdded
      )
      .subscribe(responseData => {
        this.potsUpdated.next([...this.posts]);
        this.router.navigate(["/"]);
      });
  }

The error message I'm receiving is:

Argument of type 'Date' is not assignable to parameter of type 'string | Blob'. Type 'Date' is not assignable to type 'string'.ts(2345)

or

Argument of type 'boolean' is not assignable to parameter of type 'string | Blob'.ts(2345)

and finally the error for array

Argument of type 'string[]' is not assignable to parameter of type 'string | Blob'. Type 'string[]' is not assignable to type 'string'.ts(2345)

When dealing with booleans

The booleans are used for toggles, and dates are intended for datepickers.

Any suggestions on how to handle this?

Answer №1

If you want the date to be displayed in the correct format, consider using this code snippet:

var datestr = (new Date(postAdded.startDate)).toUTCString();
formdata.append("start", datestr);

When dealing with boolean values:

formdata.append(prop, JSON.stringify(postAdded.private));

For arrays:

for (let i = 0; i < postAdded.participants.length; i ++) {
    formdata.append(prop, JSON.stringify(postAdded.participants[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

Modify the parent property's value within a derived Angular service

I'm utilizing Angular 9 and I have Service A along with Service B which extends Service A. Within Service A, there's a specific property that I aim to modify its value from within Service B. Surprisingly, the change only reflects in Service B and ...

Accessing and manipulating a intricate JSON structure within an Ionic 3 framework to seamlessly connect it to the user

I'm currently developing an app using Ionic 3. Within my project, I have a JSON object structured like this: { "player": { "username": "thelegend", "platform": "xbox", "stats": { "normal": { "shots ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

Issues with Webpack and TypeScript CommonsChunkPlugin functionality not functioning as expected

Despite following various tutorials on setting up CommonsChunkPlugin, I am unable to get it to work. I have also gone through the existing posts related to this issue without any success. In my project, I have three TypeScript files that require the same ...

Navigate between Angular components using [routerLink] in Angular router

How can I navigate from localhost:4200/home to localhost:4200/home#app=1111? I attempted the following: home.component.html <a class="app-card" [routerLink]="['/HOME']" [queryParams]="{'app':'1111'}"> However, nothin ...

What is the process for setting up a node test launch configuration?

I have some "node 18 test runner" tests ready to be executed. I can run them using the following command: node --loader tsx --test tests/**/*.ts To debug these tests in vscode, I realized that I need to set up a configuration entry in my launch.json. But ...

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

Utilizing class-transformer to reveal an array of objects

I am facing an issue with exposing an array of objects in my code. Even though I have exposed the Followers array in the UserDto, it is not getting displayed as expected. This is the output I am currently seeing, { "id": "5ff4ec30-d3f4- ...

Using command line arguments in a Tauri project with a Next.js frontend

I am utilizing Tauri.JS in conjunction with Next.js. In this scenario, I need to execute the console command: npm run tauri dev --<argument name>=<some value>. Afterwards, I should be able to access the value of the argument in my JavaScript ...

tips on rotating an image using nativescript

I'm attempting to insert a picture from my device and then adjust its orientation in nativescript. So far, I've been using imageSource to import the picture, but I'm unsure how to rotate it. If anyone has suggestions for another class that c ...

Steps to retrieve a date from a form control

html <form [formGroup]="searchForm" (ngSubmit)="search()"> <div class="row"> <div class="col"> <input type="date" class="form-control" formControlName="startD ...

The Angular selector is unrecognized: double-check that it belongs to the current module if it is an Angular component

After creating a component, I attempted to utilize it in another component by specifying its selector in the display segment. <app-component1></app-component1> However, I encountered a compile error. Upon reviewing the imports in the modules, ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Generate the test output and save it to the distribution folder

When setting up my Angular 9 application in a Jenkins pipeline, I include two key steps: npm run test:prod, which translates to node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod; and npm run build:prod, translating to node --ma ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

Experiment with Google Sign-In authentication in jest with Firebase

As I try to effectively mock firebase authentication with Google login, I am encountering some difficulties. Below is the code that I am currently working with: simple.tsx import React, { Component } from 'react'; import * as firebase from &apo ...

Issue with Material UI v5: Uncaught TypeError - Unable to access properties of an undefined object (specifically 'create')

After setting up the ThemeSetting.tsx context, I encountered an issue where I could not utilize <Button><Button> and other components that rely on the theme from Material UI React.js in TypeScript: error TypeError: Cannot read properties of u ...

Clicking the "X" close button on a mat-list removes an item from the user interface

Recently, I utilized the mat-list component to display items on the UI. Each item is accompanied by a close(X) button located on the right-hand side. https://i.stack.imgur.com/1E2ZG.png Html Code <mat-list > <ng-container *ngFor='le ...

Show the key and value of a JSON object in a React component

When attempting to parse a JSON data file, I encountered an error message stating: "Element implicitly has an 'any' type because expression of type 'string' can't be used to the index type." The JSON data is sourced locally from a ...