AppDividend
Latest Code Tutorials

Angular Firebase Tutorial With Example From Scratch

Angular 5 Firebase Example

6,806

Get real time updates directly on you device, subscribe now.

Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial ExampleAngular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From Scratch. We will build Stock Market Application where the user can insert and display the share price from the Firebase.  It is just a skeleton that demonstrates how to do a most common operation with Angular and Firebase. Firebase used a NoSQL Database.

Angular Firebase Tutorial

As we know, Angular uses TypeScript Language, which is a superset of Javascript. It transpiles the TypeScript code into the Javascript code with the help of webpack. We will start by installing Angular and configure the Firebase with Angular and build the Angular Firebase Project.

Step 1: Install the Angular.

You need to set up a dev environment before you can do anything. Install Node.js® and npm if they are not already on your machine.Then install the Angular CLI globally.

npm install -g @angular/cli

Step 2. Create a new project.

Type the following command. It will create the folder structure and also install the remaining dependencies.

ng new ng5firebase

Step 3: Install Angular Firebase Module.

Hit the following command in the terminal.

npm install firebase angularfire2 --save

Step 4: Add Firebase config to environment variable.

Open /src/environments/environment.ts and add your Firebase configuration:

// environment.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: '<your-key>',
    authDomain: '<your-project-authdomain>',
    databaseURL: '<your-database-URL>',
    projectId: '<your-project-id>',
    storageBucket: '<your-storage-bucket>',
    messagingSenderId: '<your-messaging-sender-id>'
  }
};

Step 5: Setup @NgModule for a AngularFireModule.

Replace the following code in the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { environment } from '../environments/environment';

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

Now, we have successfully configured the Firebase with an Angular application.

Step 6: Make two components of the application.

Create one directory inside src  >>  app folder called components.

Go to the root of the folder and in the console and hit the following command.

ng g c index
ng g c create

We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.

It makes a separate folder inside src  >>  app directory. We need to move all these three folders inside components folder.

Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.

Step 7: Routing and Navigation.

The Angular Router enables navigation from one view to the next as users perform application tasks.

First, we need to import the routing modules inside our app.module.ts file.

Configuration

When we have created the components, it’s by default path is different and now we have moved to the components, so now its path is different. So, first, we need to change that path in app.module.ts file.

Okay, now we need to configure the routes. So make one file inside app directory called router.module.ts file.

Write the following code in it.

// router.module.ts

import { RouterModule } from '@angular/router';
import { CreateComponent } from './components/create/create.component';
import { IndexComponent } from './components/index/index.component';

export const appRoutes: Routes = [
  { path: 'create',
    component: CreateComponent
  },
  { path: 'index',
    component: IndexComponent
  }
];

We have defined one array, and inside that array, we have registered the different routes with their components. Finally, we have exported it.

Related Posts
1 of 10

Now, import this object inside app.module.ts  and register the module.

// app.module.ts

import { appRoutes } from './router.module';

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes)
],

Step 8: Define the Router outlet.

In the app.component.html file, write the following code.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!!
  </h1>
  <nav>
    <a routerLink="create" routerLinkActive="active">Add coins</a>
  </nav>
  <router-outlet></router-outlet>
</div>

Step 9: Add Bootstrap CSS.

Download the bootstrap from its original docs and paste the CSS and JS folders inside src  >>  assets folder.
In the src >>  index.html file, add the bootstrap css file.

<link rel="stylesheet" href="assets/css/bootstrap.min.css">

Also, change the app.component.html outlook due to bootstrap classes.

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <ul class="nav navbar-nav">
      <li>
        <a routerLink="create">
          Add Share
        </a>
      </li>
      <li>
        <a routerLink="index">
          Display Shares
        </a>
      </li>
    </ul>
  </div>
</nav>

<div class="container">
  <router-outlet></router-outlet>
</div>

Step 10: Make a form in the create a component file.

First, our create.component.ts file looks like this.

// create.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  title = 'Share Market';
  constructor() { }

  ngOnInit() {
  }

}

And then, we need to make the create.component.html form design.

<div class="panel panel-primary">
  <div class="panel-body">
    <form>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" name="name"/>
      </div>
      <div class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" name="coin_price"/>
        </div>
        <div class="form-group">
          <button type="submit" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Now, head over to this. http://localhost:4200/create . It looks like this.

 

Angular 5 Firebase Tutorial

Step 11: Create services to send http requests.

Type the following command in your terminal.

ng g service share

Now, import the service file into the app.module.ts file.

import { ShareService } from './coin.service';

providers: [ShareService]

Now, first, we will insert the values in the Firebase database.Include the ReactiveFormsModule in the app.module.ts file.

// app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    RouterModule.forRoot(appRoutes),
    ReactiveFormsModule
  ],

Then, we are validating the forms. So first write the form HTML in the create.component.html. 

<div class="panel panel-primary">
  <div class="panel-body">
    <form [formGroup]="angForm" novalidate>
      <div class="form-group">
        <label class="col-md-4">Share Name</label>
        <input type="text" class="form-control" formControlName="name" #name />
      </div>
      <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
      </div>
      <div class="form-group">
        <label class="col-md-4">Share Price</label>
        <input type="text" class="form-control" formControlName="price" #price/>
      </div>
      <div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['price'].errors.required">
          Price is required.
        </div>
      </div>
        <div class="form-group">
          <button (click)="addShare(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
        </div>
    </form>
  </div>
</div>

Also, we need to write the logic of validation in the create.component.ts file.

// create.component.ts

import { Component, OnInit } from '@angular/core';
import { ShareService } from '../../share.service';
import { FormGroup,  FormBuilder,  Validators } from '@angular/forms';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {

  angForm: FormGroup;
  constructor(private shareservice: ShareService, private fb: FormBuilder) {
    this.createForm();
   }
  createForm() {
    this.angForm = this.fb.group({
      name: ['', Validators.required ],
      price: ['', Validators.required ]
   });
  }
  addShare(name, price) {
     const dataObj = {
      name: name,
      price: price
    };
    this.shareservice.addShare(dataObj);
  }
  ngOnInit() {
  }
}

Write the share.service.ts file to insert the data into the database.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  public items: any;
  public item: any;
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }
}

If all of your database configurations are right then now you can insert the values in the Firebase. You can see on your console. If you do not know how to configure the Firebase then check out my React Firebase Tutorial

Step 12: Display the shares data in our application.

Now, go to the index.component.ts file and replace the whole file with the following code.

// index.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ShareService } from '../../share.service';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {

  public shares: Observable<any[]>;
  constructor(private shareservice: ShareService) { }

  ngOnInit() {
    this.shares = this.getShares('/shares');
  }
  getShares(path) {
    return this.shareservice.getShares(path);
  }
}

Our final share.service.ts file looks like this. I have coded the fetching the data from the firebase function.

// share.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ShareService {

  private basePath = '/shares';
  constructor(private db: AngularFireDatabase) { }

  addShare(data) {
  const obj = this.db.database.ref(this.basePath);
  obj.push(data);
  console.log('Success');
  }

  getShares(path): Observable<any[]> {
    return this.db.list(path).valueChanges();
  }
}

And finally, our view file index.component.html looks like this.

<table class="table table-striped">
  <tr>
    <th>Share Name</th>
    <th>Share Price</th>
  </tr>
  <tr *ngFor="let share of shares | async">
    <td>{{ share.name }}</td>
    <td>{{ share.price }}</td>
  </tr>
</table>

 

Firebase Angular Tutorial Example From Scratch

Fork Me On Github

That is it, Guys. Angular Firebase Tutorial With Example From Scratch is over. Thanks.

.

 

 

 

7 Comments
  1. Katheirne says

    Has anyone else gotten a “Cannot read property ‘loadChildren’ of null” error when trying this tutorial?

    1. Krunal says

      Try to edit the app.module.ts file by just hit the space anywhere and save it and then webpack will automatic restart the compiling and your problem will be resolved.

  2. A Eche says

    Hi, Im getting an error “cannot find name “Routes” on the router.module.ts file

    1. Walter Torres says

      Change the line in “router.module.ts” to read…

      import{ RouterModule, Routes } from “@angular/router”;

  3. Walter Torres says

    Module not found: Error: Can’t resolve ‘./coin.service’

    any ideas?

    1. Amanda Brown says

      Hey, it looks like it’s actually supposed to be `import { ShareService } from ‘./share.service’`, the ts file that’s automatically created when did `ng g service share`. Hope that helps!

  4. jake says

    thanks , i had to make some changes but saved me alot of work

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.