Angular 11 Google OAuth Social Login Example

By Hardik Savani October 20, 2023 Category : Angular

Hi Dev,

Today our leading topic is angular 11 login with google. you will learn how to login with google in angular 11. you will learn angular 11 social login gmail. if you want to see example of login with gmail in angular 11 then you are a right place.

You have to follow few step to give login with google account in angular 11 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 work.

I hope it can help you...

Shares