Angular Login with Google Account Example

By Hardik Savani October 20, 2023 Category : Angular

This post will give you example of angular login with google. you can understand a concept of how to login with google in angular. Here you will learn angular social login gmail. In this article, we will implement a login with gmail in angular.

You have to follow few step to give login with google account in angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 application. let's follow bellow simple step:

Preview:

Step 1: Create Google App

Here you need to create google app and get client id and secret. so let's go to Google Console.

Now let's see one by one screen shot show you:

Step 2: app/app.component.ts

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 {

title = 'loginGoogle';

auth2: any;

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

constructor() { }

ngOnInit() {

this.googleAuthSDK();

}

callLoginButton() {

this.auth2.attachClickHandler(this.loginElement.nativeElement, {},

(googleAuthUser) => {

let profile = googleAuthUser.getBasicProfile();

console.log('Token || ' + googleAuthUser.getAuthResponse().id_token);

console.log('ID: ' + profile.getId());

console.log('Name: ' + profile.getName());

console.log('Image URL: ' + profile.getImageUrl());

console.log('Email: ' + profile.getEmail());

/* Write Your Code Here */

}, (error) => {

alert(JSON.stringify(error, undefined, 2));

});

}

googleAuthSDK() {

window['googleSDKLoaded'] = () => {

window['gapi'].load('auth2', () => {

this.auth2 = window['gapi'].auth2.init({

client_id: 'YOUR CLIENT ID HERE',

cookiepolicy: 'single_host_origin',

scope: 'profile email'

});

this.callLoginButton();

});

}

(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'));

}

}

Step 3: app/app.component.html

<div class="container mt-5">

<h1>Google Login with Angular - ItSolutionStuff.com</h1>

<div class="row mt-5">

<div class="col-md-4 mt-2 m-auto ">

<button class="btn btn-danger" #loginRef>

Login with Google

</button>

</div>

</div>

</div>

Let's try it. it will works.

I hope it can help you...

Tags :
Shares