JorisSchelfaut / angular-dev-tutorial-first-app

Project following the Angular tutorial on angular.io
MIT License
0 stars 0 forks source link

Integrate Angular forms #12

Closed JorisSchelfaut closed 3 months ago

JorisSchelfaut commented 4 months ago

1. Add a method to send form data

This step adds a method to your app's service that receives the form data to send to the data's destination. In this example, the method writes the data from the form to the browser's console log. In the Edit pane of your IDE:

  1. In src/app/housing.service.ts, inside the HousingService class, paste this method at the bottom of the class definition.
      submitApplication(firstName: string, lastName: string, email: string) {
        console.log(
          `Homes application received: firstName: ${firstName}, lastName: ${lastName}, email: ${email}.`,
        );
      }
  2. Confirm that the app builds without error. Correct any errors before you continue to the next step.

2. Add the form functions to the details page

This step adds the code to the details page that handles the form's interactions. In the Edit pane of your IDE, in src/app/details/details.component.ts:

  1. After the import statements at the top of the file, add the following code to import the Angular form classes.

    import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
  2. In the DetailsComponent decorator metadata, update the imports property with the following code:

    imports: [CommonModule, ReactiveFormsModule],
  3. In the DetailsComponent class, before the constructor() method, add the following code to create the form object.

      applyForm = new FormGroup({
        firstName: new FormControl(''),
        lastName: new FormControl(''),
        email: new FormControl(''),
      });

    In Angular, FormGroup and FormControl are types that enable you to build forms. The FormControl type can provide a default value and shape the form data. In this example firstName is a string and the default value is empty string.

  4. In the DetailsComponent class, after the constructor() method, add the following code to handle the Apply now click.

      submitApplication() {
        this.housingService.submitApplication(
          this.applyForm.value.firstName ?? '',
          this.applyForm.value.lastName ?? '',
          this.applyForm.value.email ?? '',
        );
      }

    This button does not exist yet - you will add it in the next step. In the above code, the FormControls may return null. This code uses the nullish coalescing operator to default to empty string if the value is null.

  5. Confirm that the app builds without error. Correct any errors before you continue to the next step.

3. Add the form's markup to the details page

This step adds the markup to the details page that displays the form. In the Edit pane of your IDE, in src/app/details/details.component.ts:

  1. In the DetailsComponent decorator metadata, update the template HTML to match the following code to add the form's markup.

      template: `
        <article>
          <img
            class="listing-photo"
            [src]="housingLocation?.photo"
            alt="Exterior photo of {{ housingLocation?.name }}"
            crossorigin
          />
          <section class="listing-description">
            <h2 class="listing-heading">{{ housingLocation?.name }}</h2>
            <p class="listing-location">{{ housingLocation?.city }}, {{ housingLocation?.state }}</p>
          </section>
          <section class="listing-features">
            <h2 class="section-heading">About this housing location</h2>
            <ul>
              <li>Units available: {{ housingLocation?.availableUnits }}</li>
              <li>Does this location have wifi: {{ housingLocation?.wifi }}</li>
              <li>Does this location have laundry: {{ housingLocation?.laundry }}</li>
            </ul>
          </section>
          <section class="listing-apply">
            <h2 class="section-heading">Apply now to live here</h2>
            <form [formGroup]="applyForm" (submit)="submitApplication()">
              <label for="first-name">First Name</label>
              <input id="first-name" type="text" formControlName="firstName" />
              <label for="last-name">Last Name</label>
              <input id="last-name" type="text" formControlName="lastName" />
              <label for="email">Email</label>
              <input id="email" type="email" formControlName="email" />
              <button type="submit" class="primary">Apply now</button>
            </form>
          </section>
        </article>
      `,

    The template now includes an event handler (submit)="submitApplication()". Angular uses parentheses syntax around the event name to define events in the template code. The code on the right hand side of the equals sign is the code that should be executed when this event is triggered. You can bind to browser events and custom events.

  2. Confirm that the app builds without error. Correct any errors before you continue to the next step.

image

4. Test your app's new form

This step tests the new form to see that when the form data is submitted to the app, the form data appears in the console log.

  1. In the Terminal pane of your IDE, run ng serve, if it isn't already running.
  2. In your browser, open your app at http://localhost:4200.
  3. Right click on the app in the browser and from the context menu, choose Inspect.
  4. In the developer tools window, choose the Console tab. Make sure that the developer tools window is visible for the next steps
  5. In your app:
    1. Select a housing location and click Learn more, to see details about the house.
    2. In the house's details page, scroll to the bottom to find the new form.
    3. Enter data into the form's fields - any data is fine.
    4. Choose Apply now to submit the data.
  6. In the developer tools window, review the log output to find your form data.