2

I have a simple form and I'm using EmailJS to handle it and I'm sure my IDs and key are correct.

Here's an example of my form:

<form (ngSubmit)="sendEmail(form)" #form="ngForm">
    
    <div class="form-group">
        <label for="user_name">Name:</label>
        <input type="text" id="user_name" name="user_name" ngModel required>
    </div>

    <div class="form-group">
        <label for="user_email">E-Mail:</label>
        <input type="email" id="user_email" name="user_email" ngModel required>
    </div>

    <div class="form-group">
        <label for="message">Message:</label>
        <textarea id="message" name="message" ngModel required></textarea>
    </div>

    <button type="submit" [disabled]="!form.valid">Senden</button>
       
</form>

And here's my component code (contact.component.ts):

import { Component, ViewChild, ElementRef } from '@angular/core';
import emailjs from '@emailjs/browser';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrl: './contact.component.css'
})
export class ContactComponent {
  @ViewChild('form', { static: true }) formRef: ElementRef | undefined;
  
  successMessage: string | null = null;
  errorMessage: string | null = null;

  constructor() { }

  sendEmail(form: NgForm) {
    if (form.valid && this.formRef) {
      emailjs.sendForm('SERVICE_ID', 'TEMPLATE_ID', this.formRef.nativeElement, 'PUBLIC_KEY')
        .then(() => {
          this.successMessage = 'Your messa has been sent successfuly!';
          this.errorMessage = null;
          form.resetForm();
        }, (error) => {
          this.errorMessage = 'Error response: ' + error.text;
          this.successMessage = null;
        });
    }
  }

}

I can't send my email because the formRef always shows NULL. I asked Gemini and it says the problem is with timing, the method needs a little more time to build the formRef and nativeElement.

Can you help me with this? The problem is with `formRef.

2 Answers 2

0

Try setting static to false (Default), so that it always takes the latest value.

@ViewChild('form') formRef: ElementRef | undefined;

The [docs] says:

static - true to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.


Another alternative,directly use the target property of the submit event.

HTML:

<form (ngSubmit)="sendEmail($event)" #form="ngForm" formElement>

TS:

    public sendEmail(e: Event) {
      emailjs
        .sendForm(
          'YOUR_SERVICE_ID',
          'YOUR_TEMPLATE_ID',
          e.target as HTMLFormElement,
          'YOUR_USER_ID'
        )
        .then(
          (result: EmailJSResponseStatus) => {
            console.log(result.text);
          },
          (error) => {
            console.log(error.text);
          }
        );
    }

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for the help. After trying everything, I did some tests and Gemini suggested to use send() method instead of sendForm() method and also change this.formRef.nativeElement to form.value:

sendEmail2(form: NgForm) {
    if (form.valid) {
      // Verwenden der send()-Methode mit den Daten aus dem Formular
      emailjs.send('SERVICE_ID', 'TEMPLATE_ID', form.value, 'PUBLIC_KEY')
        .then(() => {
          this.successMessage = 'Your Message has been sent successfully!';
          this.errorMessage = null;
          form.resetForm();
        }, (error) => {
          this.errorMessage = 'An error has occurred: ' + error.text;
          this.successMessage = null;
        });
    } else {
      this.errorMessage = 'Please fill in all required fields!';
    }
  }

After that, it worked very well

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.