Angular Google login with example

Today we will discuss about Google login in Angular 8. We will use JS SDK of Google for the login. This going to be very easy with Angular Google Login tutorial. So let’s get start with the angular google login with example. This tutorial will work for Angular 7 and 8

Before start Google login in Angular 8. We need a Angular 8 Project. If you don’t know how to create a new angular 8 project. Follow this tutorial.

Create Client ID

Before you can integrate Google Sign-In into your website, you must create a client ID, which you need to call the sign-in API.

To create a Google API Console project and client ID, go to the APIs & Services dashboard and then follow the below video:

Add a Placeholder

We need to add a placeholder for the signin button. To add the placeholder open app.component.html file and put the below html markup

<div class="container mt-5">
  <h2>Google Login</h2>
  <div class="row mt-5">
    <div class="col-md-4 mt-2 m-auto ">
        <button class="loginBtn loginBtn--google" #loginRef>
            Login with Google
          </button>
    </div>    
  </div>
</div>

Next, Open the app.component.ts file and add the below code

@ViewChild('loginRef', {static: true }) loginElement: ElementRef;

Access <div #loginRef>: loginElement is a reference to <div #loginRef> inside app.component.html file. ViewChild directive creates a direct link between <div> element and a loginElement member variable.

Load the Google Platform Library

Add the below method in your component.ts file. I am going to add in my app.component.ts file

googleSDK() {

  window['googleSDKLoaded'] = () => {
    window['gapi'].load('auth2', () => {
      this.auth2 = window['gapi'].auth2.init({
        client_id: 'YOUR_CLIENT_ID',
        cookiepolicy: 'single_host_origin',
        scope: 'profile email'
      });
      this.prepareLoginButton();
    });
  }

  (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'google-jssdk'));

}

Here, Change the YOUR_CLIENT_ID with your client id, Which we have created at the start of this tutorial.

You may notice that We have created a googleSDKLoaded method. We have set the callback when the Google Platform Library will loaded. This method will initialize the google login

Next, Call the above method from then ngOnInit () method

ngOnInit() {
  this.googleSDK();
}

Attach Click Handler

Add the below method in your component.ts file. I am going to add in my app.component.ts file

prepareLoginButton() {

  this.auth2.attachClickHandler(this.loginElement.nativeElement, {},
    (googleUser) => {

      let profile = googleUser.getBasicProfile();
      console.log('Token || ' + googleUser.getAuthResponse().id_token);
      console.log('ID: ' + profile.getId());
      console.log('Name: ' + profile.getName());
      console.log('Image URL: ' + profile.getImageUrl());
      console.log('Email: ' + profile.getEmail());
      //YOUR CODE HERE


    }, (error) => {
      alert(JSON.stringify(error, undefined, 2));
    });

}

You might noticed that We have already call this method inside the ` googleSDKLoaded .

This method will attach the click handler. When user click on Google signin button google will open the login dialog box.

After the complete all the above steps, our component will looks like this

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

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

  auth2: any;

  @ViewChild('loginRef', {static: true }) loginElement: ElementRef;

  constructor() { }

  ngOnInit() {

    this.googleSDK();
  }

  prepareLoginButton() {

    this.auth2.attachClickHandler(this.loginElement.nativeElement, {},
      (googleUser) => {

        let profile = googleUser.getBasicProfile();
        console.log('Token || ' + googleUser.getAuthResponse().id_token);
        console.log('ID: ' + profile.getId());
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
        //YOUR CODE HERE


      }, (error) => {
        alert(JSON.stringify(error, undefined, 2));
      });

  }
  googleSDK() {

    window['googleSDKLoaded'] = () => {
      window['gapi'].load('auth2', () => {
        this.auth2 = window['gapi'].auth2.init({
          client_id: '188637199174-dnm6dm1r7k652d8ddqd122kgas9kho3e.apps.googleusercontent.com',
          cookiepolicy: 'single_host_origin',
          scope: 'profile email'
        });
        this.prepareLoginButton();
      });
    }

    (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://apis.google.com/js/platform.js?onload=googleSDKLoaded";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'google-jssdk'));

  }

}

Running application:

Run the application using ng serve --o

Preview

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *