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

39 Comments

  1. Lion said:

    Do you save user information in database?

    September 11, 2019
    Reply
    • w3path said:

      No, We don’t save any information in database

      September 13, 2019
      Reply
  2. john said:

    got this working. great! it’s worth highlighting that the –o option on “ng serve” is important for firefox as it prevents a “popup_closed_by_user” error

    March 16, 2020
    Reply
  3. David said:

    Hi, can you help me?
    I need to know how to log out of google.
    I have been seeing many examples and so far only the login you show in your example works for me.
    please.

    June 5, 2020
    Reply
  4. Smit said:

    This is not working in google chrome incognito mode

    September 3, 2020
    Reply
  5. MixDrext said:

    thx much for the invitation :).
    PS: How are you? I am from France 🙂 very good forum 🙂 mixx

    November 26, 2020
    Reply
  6. wooDok said:

    hi, i am woo from Sweden and i want to explain any thing about “pandemic”. Please ask me 🙂

    December 3, 2020
    Reply
  7. HeliElith said:

    Cialis Se Vende Con Receta Eraveden cheapest cialis fradrady Cialis Precio En Farmacia

    December 20, 2020
    Reply
  8. hemp oil said:

    I needed to post you that little bit of observation to say thanks once again for your personal magnificent pointers you’ve featured in this article. It is quite remarkably generous of people like you to give openly just what a number of us might have marketed as an e book to generate some dough for themselves, most notably given that you could possibly have done it if you ever decided. These points as well served to be a fantastic way to fully grasp other people have similar fervor much like my own to know the truth lots more pertaining to this issue. I am certain there are millions of more fun opportunities in the future for individuals who looked at your blog post. https://nujemznuedi.online/

    January 7, 2021
    Reply
  9. tadalafil cheap said:

    I am just writing to make you understand what a notable experience my wife’s girl had using your web site. She mastered so many pieces, which included what it is like to possess an excellent helping nature to let other people with ease learn some problematic things. You truly surpassed people’s expected results. Thank you for producing these precious, trusted, informative and in addition fun tips about that topic to Emily. https://hillsdaledowcenter.com/

    January 7, 2021
    Reply
  10. buy tadalafil said:

    I am just writing to make you understand what a outstanding experience my wife’s girl obtained using your web site. She noticed so many pieces, which included what it is like to possess an excellent helping nature to let other people with ease learn specific specialized things. You truly surpassed people’s expected results. Thank you for producing these precious, trusted, informative and in addition fun tips about this topic to Lizeth. https://hillsdaledowcenter.com/

    January 7, 2021
    Reply
  11. tofranil prices said:

    My spouse and i got quite glad that Ervin could deal with his investigations through the ideas he got out of the web page. It’s not at all simplistic to just continually be giving freely key points that many other people have been selling. And we also fully grasp we have got the website owner to be grateful to for that. The entire explanations you have made, the simple site menu, the friendships you can help foster – it’s got many great, and it’s really helping our son and the family imagine that the issue is entertaining, and that is particularly indispensable. Thank you for everything! https://tofranilimipramine.com/#

    January 9, 2021
    Reply
  12. venlafaxine buy said:

    Thank you for your entire labor on this web site. My mom take interest in participating in investigations and it is obvious why. My partner and i learn all regarding the lively tactic you produce simple thoughts through your web site and in addition invigorate response from the others on the subject then our favorite princess is truly studying a whole lot. Take advantage of the rest of the year. You have been doing a superb job. https://venlorz.com/#

    January 9, 2021
    Reply
  13. wooDok said:

    https://fortnite-skins-for-free-2021.mystrikingly.com/

    Informative Tips on Finding A great Desktop Computer For A great Deal

    When buying a computer, you may enter the accretion and look rows and rows of desktop machines. This can leave you feeling vertigo as you attempt to decipher which is your best bet. on the other hand of facing this dilemma, use the tips under to craft a plan which helps you acquire a good deal.

    When searching for a desktop computer be clear to shop around. bearing in mind the growing popularity of laptops, tablets, and mobile devices, desktops have fallen out of favor. As such, sales are struggling. Use this to your advantage and see for the best deals out there considering purchasing a supplementary desktop computer.

    If you gone playing games online and want to purchase a gaming computer, you obsession to remember some things. make certain the computer has a video card that’s good, a memory of a minimum of 4 GB, and a firm display that’s high. There are as well as keyboards that are build up to maximize your experience.

    As you see for the right desktop computer for your needs, pay near attention to your designed type of Internet connection as with ease as whether or not a potential desktop model has a modem. If you are not adept to be next to to broadband due to your location, you will craving a modem. Otherwise, you can buy a computer that does not have one.

    If you desire to save maintenance upon your desktop computer, see into buying a refurbished model. These computers are ones that have been definite at the factory and are often offered at a steep discount. These are usually offered by the computer brands upon their own websites, in view of that assume a look past you buy a supplementary computer.

    If you desire to extend the sparkle of your potential desktop computer, make clear you pick one that is upgradeable. There are more than a few desktops these days that seal admission to the inner workings of the machine. That means no capability to upgrade. Check that you’ve got right of entry prior to buying.

    If you compulsion a more powerful computer, look in areas listed as “gaming” or “entertainment” computers. These will have more RAM and faster processors which can handle these tasks. If you buy a computer listed as an “everyday” machine, you’ll locate that it just doesn’t rouse going on to your needs.

    Try online comparison shopping once you craving a desktop computer. Using comparison sites that be active what a certain model offers across compound brands can incite you you find where to buy. It can as a consequence keep you a lot of money. determined sites may have the funds for useful additions and clear shipping.

    The computer world keeps changing, and a desktop computer is now cheaper than a lot of laptops. You can get a great computer for below 500 dollars. purchase it from a trusted growth to ensure that full sustain is offered.

    When buying a used computer, be certain to tolerate it apart to check all of its components. look at the ports, the engagement and the boards inside to see if everything obvious is wrong. Don’t know what to look for? Check out Google Images since you go to the seller.

    Find out if the desktop computer you desire has included programs. You obsession to know what they are. You dependence to know if it has a word processor or spreadsheet program that you will use. This is important to many for their work. Also, find out if the software included are full versions or demos. The demos expire after 30 or 90 days, which require you to buy the full versions yourself.

    KW:
    Best Free Skins In FORTNITE 2021
    Free FORTNITE Skins No Human Verification Or Survey 2021
    Free FORTNITE Skins Generator 2021
    Free Skins Fortnite 2021
    Fortnite Free Skins Generator 2021
    Free FORTNITE Skins No Human Verification Or Survey 2021

    January 14, 2021
    Reply
  14. MixDrext said:

    I am expert of pandemic, and i can help you.
    PS: How are you? I am from France :)/ mixx

    January 15, 2021
    Reply
  15. steveclarke said:

    I?m not that much of a online reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your website to come back in the future.
    Cheers Life Experience Degree

    January 21, 2021
    Reply
  16. Georgina said:

    Hi i am kavin, its my first time to commenting anyplace, when i read this post
    i thought i could also make comment due to this sensible
    paragraph.

    My web site – sniper facebook

    January 30, 2021
    Reply
  17. Denae Salz said:

    This is a very interesting article. Please, share more like this!

    February 1, 2021
    Reply
  18. Jbbvguany said:

    drugstore online shopping viagra pharmacy 100mg prescription drugs without prior prescription

    February 3, 2021
    Reply
  19. Donaldcep said:

    Very good written paragraph

    free robux

    February 17, 2021
    Reply

Leave a Reply

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