The FormGroup is experiencing issues with the functionality of the Submit button

I've been working on creating a FormGroup, but I've encountered an issue with the submit button not functioning as expected. The component in question is named create. Any idea what could be causing this problem?

create.component.html


<form (ngSubmit)="addPost(postsForm.value)" [formGroup]="postsForm">
  <p>Fill out the form</p>

  <label for="title">Title</label>
  <input type="text" formControlName="title" />

  <label for="content">Content</label>
  <textarea formControlName="content"></textarea>

  <label for="cover" class="cover">Choose a file</label>
  <input
    type="file"
    name="cover"
    id="cover"
    (change)="handleInput(event)"
    formControlName="cover"
  />

  <input type="submit" value="Submit" />
</form>

create.component.ts

import { Component, OnInit } from '@angular/core';
import { DesignService } from '../design.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
    selector: 'ngx-create',
    templateUrl: './create.component.html',
    styleUrls: ['./create.component.scss']
})

export class CreateComponent implements OnInit {
    constructor(private service: DesignService) {}

    image: any = null;

    public postForm = new FormGroup({
        title: new FormControl(''),
        content: new FormControl(''),
        cover: new FormControl('')
    });

    public handleInput($event: Event) {
        alert('handlse');
        this.image = $event.target['files'];
    }

    public addPost(data: FormData) {
        alert('this is add post');
        this.service.createPost(data, this.image);
    }

    ngOnInit() {}
}

My goal is to trigger the addPost() function upon clicking the submit button. Can you provide any assistance?

Answer №1

Your code contains a spelling error

Within your HTML, you have used

[formGroup]="postsForm"

It is supposed to be

[formGroup]="postForm"

Additionally, make sure to update it when passing to the addPost function

Answer №2

The issue arises when a formGroup is created with the name postForm.

    public postForm = new FormGroup({
       title: new FormControl(''),
       content: new FormControl(''),
       cover: new FormControl('')
    });

However, in the HTML code, the form is referred to as postsForm.

<form (ngSubmit)="addPost(postsForm.value)" [formGroup]="postsForm">

To resolve this problem, simply update the name in one of them.

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

I'm troubleshooting the index variable in my Angular project, trying to figure out why it's being interpreted as a string instead of a number when used in iterated components

I decided to turn each element of the data in the component into a card by using the *ngFor directive. <ng-container *ngFor="let card of cardsInfo; index as i"> <app-card id="{{ card.id }}" index="{{ i }}" ...

Is there a way in Angular 1.5 to compile the HTML of a parent component from within a child component?

I have created two angular components called app-menuitem and app-menu. The app-menu component contains a list of app-menuitems as its children, without using transclude. App-menuitem Component: angular.module('app') .component('appMen ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

If you're setting up a new Next.js and Tailwind CSS application, you can use the flags -e or --example to start the project as a

After several attempts at creating a Next.js app with Tailwind CSS using JavaScript, I keep getting TypeScript files. How can I prevent this error? Despite following the usual commands for setting up a Next.js project, I am consistently ending up with Typ ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

PDFJS integration in Ionic 2

Looking for guidance on integrating pdfjs into an ionic2 project. Any suggestions on how to import and use it would be greatly appreciated. Thank you! I'm familiar with using pdfjs, but I'm having trouble figuring out how to bring it into my ion ...

Choose a specific div element from a collection of dynamically generated divs in Angular

I have been working on a code to dynamically generate div elements using the *ngFor directive. Here is what I have so far: <div *ngFor = "let item of Items"> <p>Item : {{item}} </p> </div> The challenge I encountered is that w ...

Using TypeScript to pass parameter in a chained function

When using node.js, I am calling a script with `exec` from the `child_process` module. In the closed state, I need to verify if there was any error so that I can handle it properly. However, I am facing an issue where I cannot access the `error` parameter ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

When running on localhost, IE11 only shows a white screen while the other browsers function properly

I have recently completed a web-based project and successfully deployed it. The project is running on port 8080. Upon testing in Chrome, Safari, and Firefox, the project functions without any issues, and no errors are displayed in the console. However, wh ...

EventEmitter asynchronous callback

Can you attach an asynchronous callback to an EventEmitter in TypeScript or JavaScript? someEmitter.on("anEvent", async () => console.log("hello")); If so, does using an async function guarantee that the function will run asynchronously? Also, what ar ...

Modifying data within nested objects using Typescript

Imagine having an object like this: { b954WYBCC4YbsMM36trawb00xZ32: { activity1: "pending", activity2: "pending" }, ​ pby0CAqQ1hTlagIqBTQf6l2Ti9L2: { activity1: "pending", activity2: "pending" } } with the in ...

Can one assign the type of a sibling property to another property within a nested object?

In search of a solution: I am attempting to develop a function, which we'll refer to as test, designed to handle nested objects with dynamic keys on the first level. The goal is for this function to automatically suggest the type of method without req ...

Having trouble resolving TypeScript TS2322 error with Context API + useState hook in your React App?

Currently, I am working on a React Typescript project that utilizes the Context API to pass down a useState hook. export const AppContext = React.createContext(null); function App() { const [value, setValue] = React.useState(3); return ( <Ap ...

Merge ObjectA emissions with ObjectB Array using RxJS

Currently, I have a code snippet that pulls data from a web service: @Effect() searchAction$ : Observable<Action> = this._actions$ .ofType(ActionTypes.SEARCH_CASES) .do(val => this._store.dispatch(new SetLoadingAction(true))) .map(act ...

Tips for creating parameterized keys for a specific type in Typescript

I've encountered a challenge while transitioning my react-native project from Flow to TypeScript. The stumbling block is recreating this specific type from Flow: declare type ApolloData<T, nodeName: string = 'node'> = { [nodeName]: ...

What is the best way to display breadcrumb text on a new line within a pop up when the width exceeds without resorting to a scroll bar

Presently, my breadcrumb has a scrollable wrap with text overflowhttps://i.sstatic.net/dhllv.png I want to make the overflowed text continue on the next line. How can I achieve this? The CSS code I am using for the image attached is as follows: .breadcrumb ...

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...