Angular 6 Blazing-fast Websites

Having an Angular web app does have its perks in the modern web, but it can be challenging, especially with the regular updates being scheduled every 6 months, which does come with some braking changes (so be aware). 🙁 So it’s no fun for developers to constantly be updating their code base. But saying that, having a blazing fast website (or web app) does have its 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? No one! Too many people these days are impatient and I’m one of them. Reality check, if you have a website that is slow in performance and take 3 seconds or longer to load? Say goodbye to your users and potential customers, they’ll find it somewhere else. So beware, are you using decade old technology?

Start the modern development cycle, having a very-fast website is an important topic these days, and if you are deciding what library or framework to choose, first think of your needs? Play with a few different one’s and see what you need it to do? What function and interaction are needed?, the community support around it?, and so on. I have started my experience going with Angular and am now trying React (Gatsby).

Anyways moving on the topic, lets learn how to add a contact form in an 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

firebase contact form

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 api keys

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

firebase form

The result in Firebase database.

Your are good to go, Angular and Firebase Integration 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!

2 responses to “How to Add an Angular 6 Contact Form and Firebase

  1. Way cool! Some extremely valid points! I appreciate you penning this write-up
    and also the rest of the site is very good.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get a free proposal for your business