Create User with Email / Password in Angular 16 Firebase

Last Updated on by in Angular

Hello folks, In this tutorial, we will understand How to create a user with Email and Password in Firebase with Angular framework?

You can use Firebase Authentication to let your users authenticate with Firebase using their email addresses and passwords and to manage your app’s password-based accounts.

Firebase allows you to create a fast and secure authentication system with its vast API collection.

Creating a user with Firebase is very easy and straightforward. You can connect Firebase’s AngularFire2 library with your Angular application and use its powerful features throughout the app.

I will be using AngularFire2 library from the node package manager (NPM) and the latest Angular release for this tutorial.

Setup Angular App

ng new angularfirebaseproject

Your basic project will be set up after that don’t forget to get into the project directory by using the following command.

cd angularfirebaseproject

Let us generate some components in our angular app.

ng g c sign-in

ng g c sign-up

In order to remove strict type warnings or error make sure to set “strict”: false under compilerOptions property in tsconfig.json file.

You can follow this detailed article to set up the Angular project with external dependencies like Bootstrap4, FontAwesome, SASS, and NgBootstrap.

Setup AngularFire2 Library in Angular

Now, setup Firebase (AngularFire2 library) in your Angular project.

npm install @angular/fire firebase@9.16.0 --legacy-peer-deps

Once you are done setting up this library, make the connection between your Firebase account and your Angular app.

First, create src/environments/ folder and environment.ts file, then add firebase configurations in environments/environment.ts file.

export const environment = {
  production: false,
  firebase: {
    apiKey: "xxxxxxxx-xxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxx",
    databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxx",
    storageBucket: "xxxxxxxx",
    messagingSenderId: "xxxxxx",
    appId: "xxxxx",
    measurementId: "xxxxxxxxxxxxxxxx"
  }
};

Create Auth Service authentication.service.ts

ng generate service shared/services/authentication

Open app.module.ts file and register the service within the file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthenticationService } from './shared/services/authentication.service';

import { AngularFireModule } from '@angular/fire/compat';
import { AngularFireAuthModule } from '@angular/fire/compat/auth';
import { AngularFireStorageModule } from '@angular/fire/compat/storage';
import { AngularFirestoreModule } from '@angular/fire/compat/firestore';
import { AngularFireDatabaseModule } from '@angular/fire/compat/database';
import { environment } from '../environments/environment';

import { SignInComponent } from './sign-in/sign-in.component';
import { SignUpComponent } from './sign-up/sign-up.component';


@NgModule({
  declarations: [AppComponent, SignInComponent, SignUpComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFirestoreModule,
    AngularFireStorageModule,
    AngularFireDatabaseModule,
  ],
  providers: [AuthenticationService],
  bootstrap: [AppComponent],
})

export class AppModule {}

Generate Authentication Service Core File

Open authentication.service.ts file and insert the following code inside the file.

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';


@Injectable({
  providedIn: 'root',
})
export class AuthenticationService {
  constructor(
    public afAuth: AngularFireAuth // Inject Firebase auth service
  ) {}

  // Sign up with email/password
  SignUp(email, password) {
    return this.afAuth
      .createUserWithEmailAndPassword(email, password)
      .then((result) => {
        window.alert('You have been successfully registered!');
        console.log(result.user);
      })
      .catch((error) => {
        window.alert(error.message);
      });
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth
      .signInWithEmailAndPassword(email, password)
      .then((result) => {
        console.log(result);
      })
      .catch((error) => {
        window.alert(error.message);
      });
  }
}

We’ve successfully created authentication.service.ts file. I’ve created 2 methods using FirebasecreateUserWithEmailAndPassword(email, password) and signInWithEmailAndPassword(email, password) APIs.

  • SignUp(email, password): This method creates a new user with email and password using Firebase API with Angular.
  • SignIn(email, password): This method allows a user to sign in with email and password.

Set Up Auth Components

We are going to sign up using our custom API. Go to your signup.component.ts file and add the following code.

import { Component } from '@angular/core';
import { AuthenticationService } from '../shared/services/authentication.service';

@Component({
  selector: 'app-sign-up',
  template: ` <div class="authBlock">
    <h3>Sign Up</h3>
    <div class="formGroup">
      <input
        type="text"
        class="formControl"
        placeholder="Username"
        #userEmail
        required
      />
    </div>
    <div class="formGroup">
      <input
        type="password"
        class="formControl"
        placeholder="Password"
        #userPassword
        required
      />
    </div>

    <div class="formGroup">
      <input
        type="button"
        class="btn btnPrimary"
        value="Sign Up"
        (click)="
          authenticationService.SignUp(userEmail.value, userPassword.value)
        "
      />
    </div>
  </div>`,
})

export class SignUpComponent {
  constructor(public authenticationService: AuthenticationService) {}
}

We are going to sign in using our custom API. Go to your signin.component.ts file and add the following code.

import { Component } from '@angular/core';
import { AuthenticationService } from '../shared/services/authentication.service';

@Component({
  selector: 'app-sign-in',
  template: ` <div class="authBlock">
    <h3>Sign Up</h3>
    <div class="formGroup">
      <input
        type="text"
        class="formControl"
        placeholder="Username"
        #userEmail
        required
      />
    </div>
    <div class="formGroup">
      <input
        type="password"
        class="formControl"
        placeholder="Password"
        #userPassword
        required
      />
    </div>
    
    <div class="formGroup">
      <input
        type="button"
        class="btn btnPrimary"
        value="Sign Up"
        (click)="
          authenticationService.SignUp(userEmail.value, userPassword.value)
        "
      />
    </div>
  </div>`,
})

export class SignInComponent {
  constructor(public authenticationService: AuthenticationService) {}
}

Make sure to evoke the auth components by adding the given tags in app.component.ts file.

<app-sign-in></app-sign-in>

<app-sign-up></app-sign-up>

You can download the full code of this tutorial from GitHub.