SendGrid Angular

👀

This tutorial is an extension of the SendGrid Transactional Email Guide. You must have the Cloud Functions deployed to start sending email from your frontend app.

Initial Setup

Make sure you have AngularFire installed in your project. Then include functions and auth in the main app module.

file_type_ng_component_ts app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFireFunctionsModule } from '@angular/fire/functions';

import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireAuthModule,
    AngularFireFunctionsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Transactional Email Component

file_type_ng_component_ts app.component.ts
import { Component } from '@angular/core';
import { AngularFireFunctions } from '@angular/fire/functions';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase/app';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(public afAuth: AngularFireAuth, private fun: AngularFireFunctions) {}



  loginWithGoogle() {
    this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }

  sendEmail() {
    const callable = this.fun.httpsCallable('genericEmail');
    callable({ text: 'Sending email with Angular and SendGrid is fun!', subject: 'Email from Angular'}).subscribe();
  }
}

The HTML provides simple conditional logic to display separate templates for logged-in and logged-out users.

file_type_html app.component.html
<h2>SendGrid Transactional Email with Angular</h2>


<div *ngIf="(afAuth.authState | async) as user; else login;">

    {{ user | json }}

    <hr>

    <button (click)="sendEmail()">Send Email with Callable Function</button>
    <button (click)="afAuth.auth.signOut()">SignOut</button>

  
</div>

<ng-template #login>
  <button (click)="loginWithGoogle()">SignIn with Google</button>
</ng-template>

Q&A Chat