Angular 4 with Firebase

Md Fahreyad Hossain
Oceanize Lab Geeks
Published in
4 min readDec 29, 2017

--

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';// New imports to update based on AngularFire2 version 4
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
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. As of AngularFire2 version 4, we have to import AngularFireDatabaseModule and AngularFireAuthModule as well.

You also need to add AngularFire, AngularFireDatabaseModule, and AngularFireAuthModule to the imports array in ngModule :

imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule
],

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:

Note: The following import structure is based on the new AngularFire 2 v4

import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';

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:

user: Observable<firebase.User>;
items: FirebaseListObservable<any[]>;
msgVal: string = '';
constructor(public afAuth: AngularFireAuth, public af: AngularFireDatabase) {
this.items = af.list('/messages', {
query: {
limitToLast: 50
}
});
this.user = this.afAuth.authState; }

First, we create 3 properties. items stores the Firebase list. user will allow us to access the user state, and msgVal stores the user-submitted entry.

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

this.user = this.afAuth.authState; allows us to check the authentication state.

Underneath our constructor, let’s paste in 3 methods: (Again, this is based on AngularFire2 v4)

login() {
this.afAuth.auth.signInAnonymously();
}
logout() {
this.afAuth.auth.signOut();
}
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. You can also choose to sign in with other providers and not just anonymously. This includes Google, Twitter, Facebook, Github, custom email, etc..

Then we log the userout with the logout() method.

Then we create a Send method 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="!(user | async)?.uid">Anonymous Login</button>
<button (click)="logout()" *ngIf="(user | async)?.uid">Logout</button>
<input type="text" id="message" *ngIf="(user | async)?.uid" 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>

The ngIf attributes placed on the login and logout buttons check in real time if the user is logged in or not.

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 web font 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!

--

--