08 May

Angular Contact Component

Angular2
In one of my older posts I showed you how to easy it is to create a carousel in Angular with Bootstrap.
In this post I want to show you how to create a simple contact form using Angular which can be used with any modern API.



The component

contactform.component.html

We’ll start off with a simple contact form. I’m asking the user for his name, e-mail address, a subject and of course the message itself.
You’ll notice that I’m also using a bit of Bootstrap CSS classes. You however can of course use anything you want to style the contact form.

<div class="col-10 offset-1">
    <form #f="ngForm" (ngSubmit)="onSubmit()">
        <div class="row">
            <div class="col-12 col-sm-6 form-group required">
                <label for="name">Name</label>
                <input type="text" [disabled]="loading" [(ngModel)]="contact.Name" name="contact.Name" required="" class="form-control text-input"
                    id="name" placeholder="Name" />
            </div>
            <div class="col-12 col-sm-6 form-group required">
                <label for="email">E-mail</label>
                <input type="email" [disabled]="loading" [(ngModel)]="contact.Email" name="contact.Email" required=""
                    class="form-control text-input" id="email" placeholder="E-mail" />
            </div>
        </div>
        <div class="row">
            <div class="col-12 form-group required">
                <label for="subject">Subject</label>
                <input type="text" [disabled]="loading" [(ngModel)]="contact.Subject" name="contact.Subject" required=""
                    class="form-control text-input" id="subject" placeholder="Subject" />
            </div>
        </div>
        <div class="row">
            <div class="col-12 form-group required">
                <label for="message">Message</label>
                <textarea type="text" [disabled]="loading" [(ngModel)]="contact.Message" name="contact.Message" required=""
                    class="form-control" id="message" placeholder="Message..."></textarea>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <button type="submit" [disabled]="loading" class="btn btn-success">Send</button>
            </div>
        </div>
    </form>
</div>


contact.component.ts

The component is quite simple.
It’ll send the data to a contactservice and subscribe on the observable.

import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';

import { ContactService } from './contact.service';
import { Contact } from './models/contact.model';

@Component({
    selector: 'contactform',
    templateUrl: './contactform.component.html',
    //This is just for styling and will add the class "row" to the parent-tag
    host: { 'class': 'row' }
})
export class ContactFormComponent implements OnInit {
    contact: Contact = new Contact();
    loading = true;

    constructor(private contactService: ContactService, private toastr: ToastrService) { }

    ngOnInit() {
        this.loading = false;
    }

    onSubmit() {
        this.loading = true;
        //Don't forget to subscribe on an observable, or it will never be called.
        this.contactService.sendMail(this.contact).subscribe(
            () => {
                //Success
                this.contact = new Contact();
                this.loading = false;
                this.toastr.success('Message send.');
            },
            () => {
                //Failed
                this.loading = false;                
                this.toastr.error('Woops, something went wrong.');
            }
        );
    }
}

contact.service.ts

The service will be the be responsible for sending the data to your API.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { retry } from 'rxjs/operators';

import { Contact } from './models/contact.model';
import { environment } from '../../environments/environment';

@Injectable()
export class ContactService {
    constructor(private http: HttpClient) { }

    sendMail(contact: Contact): Observable<object> {
        //Setting json header so other applications can parse our message.
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.post(environment.target, JSON.stringify(contact), { headers: headers })
            .pipe(
                //When it fails, we're going to retry 3 times.
                retry(3)
            );
    }
}


By using the above code you’ll be able create a contact form in Angular and make it interact most modern API’s.
Let me know your feedback or questions in the comments below and I’ll be happy to answer them!

GitHub

https://github.com/JeffreyRosselle/angular-contact-component

Leave a Reply

Your email address will not be published. Required fields are marked *