Create your account

Already have an account? Login here

Create account

Angular 4 Firebase Tutorial: Make a Simple Angular 4 App

By Gary simon - Mar 19, 2017

With the release of Angular 4, it's worth taking a fresh look at common integrations such as Firebase. Fortunately, there's absolutely nothing different required when integrating Firebase into an Angular 4 project, as compared to Angular 2.

I already have an Angular 2 Firebase tutorial and this tutorial will work with an Angular 4 project. So, check it out if you wish. 

The following tutorial will be a very similar project, with just a couple minor differences.

More Angular 4 Tutorials

If you prefer watching a video tutorial instead..

Please subscribe to the youtube channel for more awesome videos!

Set up the Firebase Project

I've gone through this Firebase Setup in detail at the other tutorial. For the most part, it's going to be the same exact process, so I'm not going to bother rewriting everything. So visit that tutorial and follow the steps all the way until you reach the "SIGN-IN METHOD" tab.

Instead of enabling Facebook, we're going to use the Anonymous option instead. So, make sure that is enabled. This also means you can ignore the Facebook Developers configuration section in that tutorial.

All of the rest of the steps are exactly the same. But just to recap:

  1. Visit the Firebase Console and Create a New Project.
  2. Click Add Firebase to your web app and save the 5 keys from apiKey to messagingSenderId. Use notepad or something else.
  3. Click on the Authentication tab and enable Anonymous.
  4. Click on the Database tab and then the RULES tab at the top. Change .read and .write values to true.

Starting the Angular 4 Project

March 24, 2017+: Run "npm install -g @angular/cli" to install the Angular CLI 1.x stable release. It will install a 4.0 project by default.

Once ready, run:

> ng new what-i-do
> cd what-i-do

Once inside the project folder, run:

> npm install angularfire2 firebase --save

This uses the node package manager to install AngularFire2 and Firebase. We need both of these packages in order to communicate with Firebase.

 You can also run ng serve for live reloading in the browser as you develop the angular 4 firebase app.

Defining the Firebase Settings in Angular 4

Now, we need to open up our code editor -- I use Visual Studio Code -- and head over to the /src/app/app.module.ts file:

import { AngularFireModule } from 'angularfire2';

export const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  storageBucket: "",
  messagingSenderId: ""
};

This imports the AngularFire2 package we installed with npm, and also allows us to define the necessary settings for our Firebase project. Paste in the details that you saved earlier from the Firebase console. 

You also need to add AngularFire to the imports array in ngModule :

imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AngularFireModule.initializeApp(firebaseConfig)    // <-Add that guy
  ],

Component Imports

Let's head over to the /src/app/app.component.ts file and at the top, add the following imports underneath the first import component line:

import { AngularFire, AuthProviders, AuthMethods,FirebaseListObservable } from 'angularfire2';

This imports every module we need in a single line. Simple enough!

Class Code

In the same file, we'll be working within the export class AppComponent.  

Paste the following at the beginning of the class:

  items: FirebaseListObservable<any>;
  name: any;
  msgVal: string = '';

  constructor(public af: AngularFire) {
    this.items = af.database.list('/messages', {
      query: {
        limitToLast: 50
      }
    });

    this.af.auth.subscribe(auth => { 
      if(auth) {
        this.name = auth;
      }
    });

  }

First, we create 3 properties. items stores the Firebase list. name will allow us to check if a user is logged in anonymously, and msgVal stores the user-submitted entry.

Within the constructor, we're passing in AngularFire through depedency injection, and this.items grabs the list of entries from AngularFire. We're also limiting the messages to 50 with limitToLast.

this.af.auth.subscribe allows us to check if a user is logged in. If so, we bind this.name to auth.

Underneath our constructor, let's paste in 2 methods:

 login() {
    this.af.auth.login({
      provider: AuthProviders.Anonymous,
      method: AuthMethods.Anonymous
    });
  }

  Send(desc: string) {
      this.items.push({ message: desc});
      this.msgVal = '';
  }

The first method handles a login method that will be called when a login button is clicked.

The second Send method is called when a user hits the enter key from a textfield. 

And that's it for the primary code! Now, let's head on over to the template.

The Template

Paste the following HTML in app.component.html:

<div class="row columns">
  <button (click)="login()" *ngIf="!name">Anonymous Login</button>

  <input type="text" id="message" *ngIf="name" placeholder="What is it that you do?" (keyup.enter)="Send($event.target.value)" [(ngModel)]="msgVal" />
  <div id="details-container">
      <p *ngFor="let item of items | async"><img src="../assets/images/pin.svg">{{item.message}}</p>
  </div>
</div>

If the name property doesn't exist, then show a login button. Simple!

The input uses the keyup.enter event to call the Send method and send the textfield value.

On the p tag we're using *ngFor to iterate through the list of items from the Firebase database. We're showing a pin.svg graphic and the message.

Let's also head over to /src/index.html and paste in the following within the <head> tags:

<link media="all" type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation-flex.min.css">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,500" rel="stylesheet">

This is importing the frontend framework Foundation and also a google webfont Raleway .

Let's Style This Thing

Paste the following CSS in app.component.css:

input#message {
    background:#fff;
    border:none;
    outline:none;
    box-shadow:none;
    font-size:1.6em;
    font-weight:300;
    margin-bottom: 3em;
    padding:1.2em .7em;
}

#details-container {
    display:flex;
    flex-direction: row;
    flex-wrap:wrap;
    width:100%;
}

#details-container p {
    background:#fff;
    padding:1.4em;
    color:#696969;
    margin: 12px;
    width:auto;
    min-width:200px;
}

img {
    display:block;
    margin-bottom:12px;
}

Also, head over to the /src/styles.css file and paste:

body {
    background-color:#EBEBEB;
    padding-top: 5em;
}
* {
    font-family: 'Raleway';
}
button {
    background:#008FEF;
    color:white;
    padding: 1.2em;
    width:300px;
    text-align:center;
    font-size:1.2em;
    margin-bottom: 30px;
    cursor:pointer;
}

Test it out!

It's all ready! So at the console, run ng serve and click the Login button to anonymously login. Then, type something in the textfield and hit enter.

If you followed everything correctly, it should show your result below.

This is obviously a very bare-bones version of an app, but feel free to expand on it with more functionality!


Share this post

Chat with us




Say something about this awesome post!