How to Handle Forms in Angular with MongoDB

 Handling forms in Angular and storing form data in MongoDB is a common requirement in full-stack web applications. This process typically involves integrating Angular on the front end, Node.js with Express on the backend, and MongoDB for database storage. Let’s explore how to handle forms in Angular and connect them to MongoDB step-by-step.

Create the Angular Form

In Angular, you can use either Template-driven or Reactive Forms. Reactive Forms offer more flexibility and control, so let’s focus on that.

Step 1: Create a form using FormBuilder

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

form: FormGroup;

constructor(private fb: FormBuilder) {

  this.form = this.fb.group({

    name: ['', Validators.required],

    email: ['', [Validators.required, Validators.email]],

    message: ['', Validators.required]

  });

}

Step 2: Bind the form in HTML

<form [formGroup]="form" (ngSubmit)="onSubmit()">

  <input type="text" formControlName="name" placeholder="Name" />

  <input type="email" formControlName="email" placeholder="Email" />

  <textarea formControlName="message" placeholder="Message"></textarea>

  <button type="submit">Submit</button>

</form>

2. Send Data to Backend using HTTP

Angular’s HttpClient is used to send the form data to the backend.

onSubmit() {

  if (this.form.valid) {

    this.http.post('http://localhost:3000/api/form', this.form.value)

      .subscribe(response => {

        console.log('Form submitted successfully', response);

      });

  }

}

3. Create Node.js + Express Backend

Set up an Express server to receive the data and connect to MongoDB.

const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const cors = require('cors');

const app = express();

app.use(cors());

app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/formDB');

const FormSchema = new mongoose.Schema({

  name: String,

  email: String,

  message: String

});

const Form = mongoose.model('Form', FormSchema);

app.post('/api/form', async (req, res) => {

  const form = new Form(req.body);

  await form.save();

  res.send({ message: 'Form data saved successfully!' });

});

app.listen(3000, () => console.log('Server running on port 3000'));

Conclusion

By using Angular for building forms, and Node.js with MongoDB for backend and database handling, you can efficiently manage user input and store it securely. This full-stack integration allows for building scalable and real-world applications with ease.

Learn MEAN Stack Training Course

Read more: 

Creating RESTful APIs with MEAN Stack

How Angular Integrates with Node.js in MEAN Stack

Deploying MEAN Stack Applications on Heroku

MongoDB Aggregation Framework for Beginners

MEAN Stack Interview Questions and Answers

Visit Quality Thought Training Institute
Get Direction









Comments

Popular posts from this blog

DevOps vs Agile: Key Differences Explained

How to Set Up a MEAN Stack Development Environment

Regression Analysis in Python