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.