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

Calculate the date input in Angular 7 by subtracting calendar days

As a user of this Angular 7 application, you are required to choose a date from a calendar input and then determine what day it was 40 days ago. Unfortunately, I have not been able to accomplish this in Typescript yet. There are numerous JavaScript solutio ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...

The error message "Unable to adjust headers once they have been sent. Angular Universal ExpressJS" appears

I am trying to implement a 404 error response in my Angular 5 component with server-side rendering. In my server.js file, I have set up the following: app.engine('html', (_, options, callback) => { let engine = ngExpressEngine({ bootst ...

Deactivating Chrome Autofill once more in version 70.0.3538.67

Unfortunately, with the latest Chrome version 70.0.3538.67, all my previous methods of disabling autofill/autosuggest no longer seem to be effective. I am looking for a clean solution that is practical and efficient. Additionally, I have forms with a com ...

Enable the parsing of special characters in Angular from a URL

Here is a URL with special characters: http://localhost:4200/auth/verify-checking/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="59663c34383035643230383d2b606a6e6b686d6e6e193e34383035773a3634">[email protected]</a> ...

Routing in Angular 2 with .NET Core

I am experiencing an issue with my ASP.NET CORE app that utilizes angular2 routing. When I run the app locally, the routes work as expected. However, once I publish it to the server (running IIS 7), the routes seem to resolve to the server root instead of ...

The invocation of `prisma.profile.findUnique()` is invalid due to inconsistent column data. An invalid character 'u' was found at index 0, resulting in a malformed ObjectID

The project I'm working on is built using Next.js with Prisma and MongoDB integration. Below is the content of my Prisma schema file: generator client { provider = "prisma-client-js" } datasource db { provider = "mongodb" url = env("DATABA ...

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Implementing secure access control in Angular based on user roles

Currently, we are working on integrating role-based security with Angular. However, we are looking for a solution to implement this on the server side to prevent users from accessing the page by manipulating JavaScript code in their browsers. While our se ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Removing an image from the files array in Angular 4: A step-by-step guide

I have recently started working with typescript and I am facing a challenge. I need to remove a specific image from the selected image files array before sending it to an API. app.component.html <div class="row"> <div class="col-sm-4" *ngFor ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...

Why is npm installing a version of Angular CLI that is incompatible with its usage?

After using nvm to install node v16.13.2, as well as npm version 8.1.2, I discovered that this setup did not include the Angular CLI by default. To rectify this, I ran npm install -g @angular/cli. However, upon checking the version of Angular CLI with ng v ...

The Proper Way to Position _app.tsx in a Next.js Setup for Personalized App Configuration

I've been working on a Next.js project and I'm currently trying to implement custom app configuration following the guidelines in the Next.js documentation regarding _app.tsx. However, I'm encountering some confusion and issues regarding the ...

The triggering of Angular Change Detection does not occur when using nested ngFor loops

Currently, I'm deeply engrossed in a substantial Angular project that utilizes NgRx Store. One interesting feature of the app is an infinite scrolling list that displays skeleton items at the end, which are later replaced by real items once the reques ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Boolean value 'isEdit' in Angular not being updated within the subscribe callback

Having a problem updating the isEdit component property within the event emitter's subscribe callback in my Angular application. Situation: In my CreateComponent, I handle adding or editing mobiles. The isEdit property (boolean) determines whether t ...

Angular2 route-driven themes

Exploring Different Themes for Two Routes: /books and /paintings Seeking a Solution to Include Specific Stylesheet Links in index.html For the /books route, I wish to include: <link rel="stylesheet" href="/assets/css/reading-theme.css" /> And for ...