Google SignIn Create a directive that extends Google SignIn to any button or element

This lesson is available for PRO members or as a single course purchase. Sign-in and choose a plan below.


*Enrollment provides full access to this course (and updates) for life.

Or Signup for Unlimited PRO Access

Steps

Step 1 - Generate the Google Signin Directive

command line
ng g directive user/google-signin

The directive listens to the click event on the host element to trigger the signin process in Firebase.

Event Types

file_type_ng_component_ts google-signin.directive.ts
import { Directive, HostListener } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase/app';

@Directive({
  selector: '[appGoogleSignin]'
})
export class GoogleSigninDirective {
  constructor(private afAuth: AngularFireAuth) {}

  @HostListener('click')
  onclick() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }
}

The directive can be attached to any button or clickable element.

Step 2 - Attach the Directive to a Button

Update the Login Page to use the directive on a material button and listen to the AngularFire user.

file_type_ng_component_ts login-page.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';

@Component({
  selector: 'app-login-page',
  templateUrl: './login-page.component.html',
  styleUrls: ['./login-page.component.scss']
})
export class LoginPageComponent {

  constructor(public afAuth: AngularFireAuth) { }

}

file_type_html login-page.component.html
  <div *ngIf="!(afAuth.authState | async)">
    <h1>Login</h1>

    <button mat-raised-button appGoogleSignin>
      <img src="/assets/google-logo.svg" /> Login with Google
    </button>
  </div>

  <div *ngIf="afAuth.authState | async as user" class="logout">
    <p>
      Logged in as <strong>{{ user.email }}</strong>
    </p>

    <button mat-stroked-button (click)="afAuth.auth.signOut()">Logout</button>
  </div>

Q&A Chat