Submitting a Form with Request Body using Angular 2

I am struggling to figure out how to send a form to an API with the body. I have managed to hard code the body so far, but I really need to dynamically retrieve values from the form and send them as the body to the API. Can someone please guide me on how to achieve this?

code

 inviteUser() {
        let headers = new Headers();
        headers.append('Content-Type','application/json');
        let body = {
            "UserName": "user1",
            "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2f293f286b1a3b2e3f3b3a1a63f222e22230a3b262a28">[email protected]</a>",
            "PartnerId": "1"
        };

        this.http.post('https://localhost:44300/api/apis/InviteUser', JSON.stringify(body), {
            headers: headers
        })
            .subscribe(
            data => this._data = data.json(),
            err => this.logError(err),
            () => console.log(body)
            );
    }

Html

<h1>Pending Approvals </h1>
<link href="../../Content/bootstrap.css" rel="stylesheet" />
<link href="../../Content/bootstrap-theme.min.css" rel="stylesheet" />
<div class="container">
    <div class="row">
        <div class="col-offset-md-10">
            <button type="button" class="btn-u  pull-center" data-toggle="modal" data-target="#myModal">Invite User</button>
        </div>

    </div>
    <div class="row">
        <div class="col-md-8">
            <div class="table-responsive">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>Account Manager</th>
                            <th>Subscription</th>
                            <th>Created By</th>
                            <th>Pending</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let user of _data">
                            <th>{{user.AccountManagerId}}</th>
                            <th>{{user.SubscriptionId}}</th>
                            <th>{{user.CreatedBy}}</th>
                            <th>
                                <button type="button" class="btn btn-xs btn-danger" (click)="approvalPendingRequest(user.SubscriptionId)">
                                    <span class="glyphicon glyphicon-send"></span>&nbsp;
                                </button>
                            
                           </th>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Add New User</h4>
            </div>
            <div class="modal-body">
                <form (submit)='inviteUser()'>
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" required
                                name="name">
                    </div>
                    <div class="form-group">
                        <label for="alterEgo">Email</label>
                        <input type="email" class="form-control" required
                                name="alterEgo">
                    </div>
                    <div class="form-group">
                        <label for="power">Partner</label>
                        <select class="form-control" 
                                 name="power">
                            <option *ngFor="let p of powers" [value]="p">{{p}}</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-default" data-dismiss="myModal">Invite</button>
                </form>
            </div>

        </div>

    </div>
</div>

https://i.sstatic.net/BlpQn.png

Detail

I am looking to dynamically pull form values and send them as the body to the API. Any help would be greatly appreciated.

Answer №1

To extract values from a form and send them using HTTP, you need to utilize Form directives and related components.

In your .html file

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">

  <div class="col-md-7">
    Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
  </div> 

  <div class="col-md-7">
    Email:   <input type="text" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password'>
  </div>

  <div class="col-md-7">
    Partner:   <input type="text" [(ngModel)]='demoInfo.partner' class="form-control" ngControl='partner'>
  </div>

</form>
<br>
<div class='text-center'>
  <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>

And in your .ts file

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'partner': new Control()
        })

After setting up the form, you can send the data using HTTP like this -

PostRequest(url,data) {
        this.headers = new Headers();
        this.headers.append("Content-Type", 'application/json');

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    return [{ status: res.status, json: res.json() }]
                }
            });
    }

For a practical example, you can refer to this Working example

Additionally, check out these resources:

  • Sending Data via HTTP in Angular 2
  • Forms in Angular 2

Answer №2

Generate form inside constructor

  form: ControlGroup;

  constructor(private fb: FormBuilder, private fba: FbaService, private router: Router) {
    this.form = this.createForm();
  }

  createForm() {
    return this.fb.group({
      "name": ["", Validators.required],
      "email": ["", Validators.required],
      "partner": [""]
    });
  }

Next, connect this form with the HTML.

<form ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
  <div class="form-group">
    <input [ngFormControl]="form.controls['name']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['name'].valid && form.controls['name'].dirty">
      Field Required
    </span>
  </div>
  <div class="form-group">
    <input [ngFormControl]="form.controls['email']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['email'].valid && form.controls['email'].dirty">
      Field Required
    </span>
  </div>
     <div class="form-group">
    <input [ngFormControl]="form.controls['partner']" type="text" class="form-control">
    <span class="text-danger" *ngIf="!form.controls['partner'].valid && form.controls['partner'].dirty">
      Field Required
    </span>
  </div> 
  <input [disabled]="!form.valid" type="submit" class="btn btn-default" value="Add">
</form>

Then utilize form.value in onSubmit.

  onSubmit(value) {
    let headers = new Headers();
    headers.append('Content-Type','application/json');

  this.http.post('https://localhost:44300/api/apis/InviteUser',value, {
        headers: headers
    })
        .subscribe(
        data => this._data = data.json(),
        err => this.logError(err),
        () => console.log(body)
        );
  }

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

What is the best way to implement a scroll event in a React application?

Can someone provide guidance on how to properly write the scrollHandler function for this scenario? ` useEffect(() => { document.addEventListener('submit', scrollHandler); return () => document.removeEventListener('scroll', ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

What is the correct method for exporting a file from the temporary folder of a node server using res.sendFile(...) or res.download(...) over HTTP?

I am facing an issue with my node/express app where the excel file I generate downloads with zero bytes via http. How can I ensure that the downloaded file has the actual data in it? My node/express code is responsible for creating an excel file and stori ...

After implementing rewrites, my dynamic routes in Next.js are no longer functioning as expected

This is the current structure of my project and it was working fine before I added rewrites to my project. https://i.sstatic.net/X989W.png -dashboard --admin --page.tsx ---[adminId] ---page.tsx --cars --page.tsx ---[carId] ---page.tsx -lo ...

When a variable is used in Postgresql, the ORDER BY clause is disregarded, but accurate results are returned when the variable value is

After investigating, it seems that the query is always returning rows ordered by id, regardless of the value passed in the sortType variable (verified in console). export async function fetchAnimalList(sortType) { noStore(); try { const areas = aw ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

What exactly is the most efficient method for validating fields within an Angular template?

My reactive form is currently displaying a validation message for each field that is not valid. However, I noticed that I was repeatedly using the check !!(!form.get(field)?.valid && form.get(field)?.touched); in every input field. So, I decided to ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...

Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser? It's important to note that the app being referred to extends http to include a JWT in ...

Facing issue in Visual Studio 2015 with Angular 2 @component not able to resolve the signature of the class decorator

Trying to define a decorator on top of my class in Visual Studio 2015 is causing an error during the build process. The specific error message states: "Build: Unable to resolve signature of class decorator when called as an expression." import { Component ...

Unable to access the suggestion list within the modal

I incorporate the PrimeNG AutoComplete feature within a PrimeNG Dialog, displaying a list of elements below the AutoComplete in the dialog. My objectives are: To set the max-height of the modal dialog to 300, and have a visible scrollbar if the total ...

Preparing an Angular 2 application for deployment on a live IIS server

After following the Angular 2 tutorial successfully and getting everything to work as expected, I realized that it doesn't cover packaging for production distribution. Is there a standard method for creating a clean distribution package without includ ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

Can Angular PWA service worker be updated even when the browser is closed?

In my Angular PWA application, I have implemented a feature that checks for service worker updates every 15 seconds to ensure the cached static files are still valid. If there is a new deployment, the service worker silently updates the cache and notifies ...

Encountering a problem in React.js and Typescript involving the spread operator that is causing an error

Could someone assist me with my current predicament? I attempted to work with TypeScript and utilize the useReducer hook. const initialState = { a: "a" }; const [state, dispatch] = useReducer(reducer, {...initialState}); I keep encountering an error ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

Developing a barrel component in React (utilizing .tsx)

My current directory structure looks like this: src assets components models counter.tsx index.ts The code found inside models/index.ts (also known as the barrel file) export * from "./counter"; The code within models/counter.ts export default in ...

To work with Typescript, the 'unknown' type needs to be equipped with

I encountered an issue in vscode stating "Type 'unknown' must have a 'Symbol.iterator' method that returns an iterator." for the following line of code: bookmarks.push(...this.$auth.user?.bookmarks); let bookmarks = []; if(this.$au ...