How to Add an Angular 6 Contact Form and Firebase

Angular 6 Blazing-fast Websites

Having a Angular web app does have it perks but it also can be challenging, especially with the regular updates being scheduled every 6 months does come with some braking changes 🙁 So its fun for developers to constantly update there code, only joking. But having a fast website does have it advantages obviously over slow sites but also with user experience being a key factor, let’s face it who likes to wait around for page reloads? so many people these days are impatient and I’m one of them. If you have a website that is slow in performance and take 3 seconds or longer to load? say goodbye to your user, they’ll find it somewhere else. Beware are you using decade old technology?

So having a blazing-fast website is an important topic and if you are deciding what platform or framework to have your website made, first think of your needs? What do you need it to do? What function and interaction are needed and so on, for greater user experience go with a blazing-fast website I ‘ve chosen Angular. Anyways moving on the topic, how to add a contact form in a Angular 6 project with Firebase.

How to add a contact form in Angular 6 to Firebase

Here I will show you how to implement a contact form in an Angular 6 project, where the information of that contact form will be sent to a database, in this case I will be using Firebase as the database.

For styling the form I will be using md-bootstrap (material bootstrap) it looks great and has built in validation.

We use the Angular CLI to start the new project called contact-form and we add routing and changing the style-sheet from .css to .scss

 ng new contact-form --routing --style=scss

Next we cd into contact-form and run:

 ng serve

We will need tp add a few dependencies, for styling and connecting with firebase

npm i angular-md-bootstarp --save
npm i firebase angularfire2 --save

Now we create a component called contact

ng g c contact

In the appModule.ts we also need to import the dependencies MD-Bootstrap, AngularFireModule and the AngularFireDatabaseModule


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ContactComponent } from ./components/pages/home/home.component';
import { AngularFireModule } from'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { MDBBootstrapModule } from'angular-bootstrap-md';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PostsComponent,
],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MDBBootstrapModule.forRoot(), 
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the contact.component.ts we first Pass in AngularFireDatabase and FormBuilder in the constructor, next we ‘ll add a property for holding the return data from the API and last we will get and bind the data to our app


import { AngularFireDatabase } from  'angularfire2/database'; 
import  { FormGroup, FormBuilder, Validators } from  '@angular/forms'; 
import  { Component } from  '@angular/core'; 
import  { Observable } from  'rxjs';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss']
})
export class ContactComponent implements OnInit {
  // Adding variables
      itemName = '';
      itemEmail = '';
      itemSubject = '';
      itemMessage = '';
      items: Observable<any[]>;
      contactForm: FormGroup;

  // Setting the database 
      constructor(private fb: FormBuilder, private db: AngularFireDatabase) {
        this.items = db.list('messages').ValueChanges()
// Passing in MD_Bootstrap form validation 
        this.contactForm = fb.group({
        contactFormName: ['', Validators.required],
        contactFormEmail: ['', [Validators.required, Validators.email]],
        contactFormSubject: ['', Validators.required],
        contactFormMessage: ['', Validators.required]
     });
       }
  // Pushing the contact-form to the firebase data base
       onSubmit()  {
       this.db.list('/messages').push({ name: this.itemName, email: this.itemEmail, subject: this.itemSubject, 
       message: this.itemMessage});
//Popup message
       alert('Thank you for contacting us, your message has gone through!')
      }
   }
// Clearing the form after submit
 clearForm() {
         this.contactForm.reset();
        }
  }

In contact.component.htmlwe add the html markup form from md-bootstrap, #notice Angulars [(ngModel)] built in directive for 2 way data binding and the onSubmit() and clearForm() click functions


     <div class="modal-header white-text">
     <h4 class="title">
     <i class="fa fa-pencil"></i>Contact Form
     </h4>
     <button type="button" class="close waves-effect waves-light" data-dismiss="modal" aria-label="Close"
     class="x" aria-hidden="true" routerLink="/home"> × </span>
     </button>
     </div>
     <div> class="card mb-5">
     <div class="md-form">
     <form [formGroup]="contactForm">


     <p class="h5 text-center mb-4">Contact info</p>
     <p id="email">e: [email protected]</p>
     <p id="phone">m: 0404 602 657</p>

     <div class="md-form">
     <i class="fa fa-user prefix grey-text"></i>
     <input type="text" id="contactFormName" formControlName="contactFormName" class="form-control" mdbInputDirective [(ngModel)]="itemName">
     <label for="contactFormName">Your name</label>
     </div>

     <div class="md-form">
     <i class="fa fa-envelope prefix grey-text"></i>
     <input type="email" id="contactFormEmail" formControlName="contactFormEmail" class="form-control" mdbInputDirective [(ngModel)]="itemEmail">
     <label for="contactFormEmail">Your email</label>
     </div>

     <div class="md-form">
     <i class="fa fa-tag prefix grey-text"></i>
     <input type="text" id="contactFormSubject" formControlName="contactFormSubject" class="form-control" mdbInputDirective [(ngModel)]="itemSubject">
     <label for="contactFormSubject">Subject</label>
     </div>

     <div class="md-form">
     <i class="fa fa-pencil prefix grey-text"></i>
     <textarea type="text" id="contactFormMessage" formControlName="contactFormMessage" class="md-textarea" style="height: 100px" mdbInputDirective [(ngModel)]="itemMessage"> 
     </textarea>
     <label for="contactFormMessage">Your message</label>
     </div>

     <div class="text-center">
     <button [disabled]="contactForm.invalid" (click)="onSubmit()" (click)="clearForm()" type="submit" class="btn waves-light" mdbWavesEffect>Send
     <i class="fa fa-paper-plane-o ml-1"></i>
     </button>
     <br>
     </div> 
     

In contact.component.scss we add the styles

.modal-header {
    margin: 0 auto;
    width: 100%;
    background-color: #33b5e5;
}

.btn {
    background-color: #33b5e5;
}

.container {
    padding-top: 100px;
}

.card {
    padding: 15px 30px;
    width: 100%;
    margin: auto;
}

#email,
#phone {
    text-align: center;
    font-family: 'Courier New', Courier, monospace;
    line-height: .5em;
}

span.x {
    color: #fff;
}

Example of the form till now

Angular 6 contact form tutorial example.

Now we need to go to the Firebase dashboard

we need to add firebase to our web app and this will generate the API key we need to insert in our Angular projects

firebase database api key example

Back in the code we go and in the enviroments.ts file we inject the api key
export const environment = {
  production: false,
  firebase: {
    apiKey: "ZXfdteuwehuwjssi_kskjdjdsj",
    authDomain: "contact-form-32637.firebaseapp.com",
    databaseURL: "https://contact-form-32637.firebaseio.com",
    projectId: "contact-form-32637",
    storageBucket: "",
    messagingSenderId: "891796435656"
 }
};
lets test the form

contact_form test firebase

The result in Firebase

firebasedatabase

Good to go Angular and Firbase Intergration Contact Form

Hope this has help you understand how to connect your Angular project with Firebase Database.

Any questions or problem leave a comment below and I’ll get back to you, happy coding! 🙂

Angular All The Way!

Leave a Comment