Build Your First Angular Website: Lesson 9 of 18

Create a Contact Page and Contact Form

Up Next

Contact Form Validations

Autoplaying in 7 seconds!

Cancel

We'll start by using the Angular CLI to generate the contact component:

ng g component components/contact

Let's get the showing part out of the way and add this to our AppComponent's template:

@Component({
  selector: 'app-root',
  template: `
    <!-- header -->
    <app-header></app-header>

    <!-- testing the contact page -->
    <app-contact></app-contact>

    <!-- testing the home page -->
    <app-home></app-home>

    <!-- routes will be rendered here -->
    <router-outlet></router-outlet>

    <!-- footer -->
    <app-footer></app-footer>
  `,
  styles: []
})
export class AppComponent {}

Now we should be able to see "contact works!" in our site.

Table of Contents

    Adding a Hero

    We want this site to look good and have a title so let's add a hero section just like we did to our home page. Here's a smaller version of the Bulma hero section. Add this to your ContactComponent's template:

    // src/app/components/contact/contact.component.ts
    
    @Component({
      selector: 'app-contact',
      template: `
        <section class="hero is-primary is-bold">
        <div class="hero-body">
        <div class="container">
    
          <h1 class="title">Contact Us!</h1>
    
        </div>
        </div>
        </section>
      `,
      styles: []
    })

    Now we can see our Contact Us hero section and contact page on our site.

    It is sitting above our home page which isn't ideal. In a following lesson, we'll handle routing so that each component only shows on its respective route:

    • ContactComponent shows for /contact
    • HomeComponent shows for /

    For now, we'll show all these components on the same page.

    Adding a Contact Form

    Now we can get to adding the contact form. We'll add it under our Contact hero section.

    <section class="section">
    <div class="container">
    
      <!-- form goes here -->
      FORM GOES HERE!
    
    </div>
    </section>

    Now that we have our foundation set, let's start talking about how we build forms in Angular.

    Angular Form Types

    There are two ways to build forms in Angular:

    Template-Driven

    This is similar to how you would have built forms in AngularJS (1.x). The data for your form will be built from the template when you use two-way data-binding.

    Reactive Forms

    Reactive forms are a more "reactive style" of programming that favors explicit management of the data. What this means is that we will tell Angular what data our form will have and then we'll apply this data to our form. This is especially useful when you need to build dynamic forms. You can adjust your form's views and fields from the component's class.

    Choosing a Form Type

    We'll use the template driven way since our contact form is only three fields. For larger forms that take more logic and more fields, I would recommend looking at the reactive way. You would build out your entire form in the class of your component instead of all in the template.

    For small forms with maybe less than five fields, it's easy to use the template driven forms. Once your form gets larger, brings in logical validation, nested form groups, and more complex things, it's recommended to use the reactive forms.

    Check out our Angular Forms and Validation Course for more info.

    Adding the Form Module

    In order to start using Angular's forms, we need to add the FormsModule to our main NgModule. This way, Angular knows which packages to bring in and make accessible to us.

    // src/app/app.module.ts
    
    import { FormsModule }   from '@angular/forms';
    
    // ...
    
    @NgModule({
      // ...
      imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule
      ],
      // ...
    })

    That's it! Now we are ready to create our form in our ContactComponent.

    Creating Our Form

    We'll build out our form with no Angular directives just yet. Add this to your ContactComponent template.

    <!-- form goes here -->
    <form>
    
      <!-- name -->
      <div class="field">
        <input type="text" name="name" class="input" placeholder="Your Name">
      </div>
    
      <!-- email -->
      <div class="field">
        <input type="email" name="email" class="input" placeholder="Your Email">
      </div>
    
      <!-- message -->
      <div class="field">
        <textarea class="textarea" name="message" placeholder="What's on your mind?"></textarea>
      </div>
    
      <button type="submit" class="button is-danger is-large">Submit</button>
    
    </form>

    The classes field, input, and textarea are Bulma classes to get our form to have some styling.

    Binding Each Input to an Angular Variable

    Now that we have our HTML done, we need to bind the values of each input to a variable in Angular. We'll use the two-way data-binding method using the affectionately named banana-in-a-box that looks like [(variableName)]. This means that our input's value will be bound to the variable inside our component's class.

    Here's our form again with the Angular directives:

    <!-- form goes here -->
    <form>
    
      <!-- name -->
      <div class="field">
        <input type="text" name="name" class="input" placeholder="Your Name" [(ngModel)]="name">
      </div>
    
      <!-- email -->
      <div class="field">
        <input type="email" name="email" class="input" placeholder="Your Email" [(ngModel)]="email">
      </div>
    
      <!-- message -->
      <div class="field">
        <textarea class="textarea" name="message" placeholder="What's on your mind?" [(ngModel)]="message"></textarea>
      </div>
    
      <button type="submit" class="button is-danger is-large">Submit</button>
    
    </form>

    Now we need to create these variables in our component class:

    export class ContactComponent implements OnInit {
      name;
      email;
      message;
    
      constructor() {}
    
      ngOnInit() {}
    
    }

    We've just added these properties to the top of our ContactComponent class. This is the ES6 way of adding properties.

    Adding Typings

    We can now add some TypeScript type-safety to make sure we know what type our properties will be:

    export class ContactComponent implements OnInit {
      name: string;
      email: string;
      message: string;
    
      constructor() {}
    
      ngOnInit() {}
    
    }

    The TypeScript stuff is optional but it can help when working through your applications, especially if your code editor supports TypeScript. You can get code hints on what types of variables you are using.

    Handling the Form Submission

    Now we can listen for this form's submission event. Listening for events is easy in Angular. We use the event-binding directive with (htmlDOMEventName).

    In this case, we can add to our <form> tag:

    <form (ngSubmit)="processForm()">

    Now whenever this form is submitted, we'll use the processForm method on our class. We have to create that now. We'll just alert the info of our form since we don't have any backend to send this info to.

    export class ContactComponent implements OnInit {
      name: string;
      email: string;
      message: string;
    
      constructor() {}
    
      ngOnInit() {}
    
      /**
       * Process the form we have. Send to whatever backend
       * Only alerting for now
       */
      processForm() {
        const allInfo = `My name is ${this.name}. My email is ${this.email}. My message is ${this.message}`;
        alert(allInfo); 
      }
    
    }
    

    We're using an ES6 template string to bring all our variables together into a message. Normally you'd use Angular's HTTP library to send this info to some backend API.

    Conclusion

    We have successfully created a new contact page with a contact form. We can data-bind our form inputs to variables. We also have the foundations to process the form!

    Next up, let's add some validation to our simple contact form.

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.