Create a User model class create a form component page test summary reference

Forms were covered in Angular Learning part 1, but that was a basic demonstration. Later, we learned about template-driven forms, so we considered refactoring the form example to make it more relevant to the application.

According to the knowledge content of template-driven forms on the official website, we rebuilt the personnel registration form, which is mainly divided into the following steps:

  1. Create the Uuser model class
  2. Create a component that controls this form
  3. Create a template with an initial form layout.
  4. usengModelThe two-way data binding syntax binds data properties to each form input control.
  5. Add to each form input controlnameAttributes (attribute).
  6. Add custom CSS to provide visual feedback.
  7. Displays and hides validation error messages.
  8. Use ngSubmit to handle form submission.
  9. Disable the submit button for this form until the form is valid.

Create the User model class

Use the Angular CLI command ng g class to generate a new class named Uuer:

ng g class model/uuer

Copy the code

As follows:

export class Uuser {



  constructor(

    public name: string.

    public sex: string.

    public city: string.

    public hobbies: any[],

    public remark: string

  ) {



  }

}

Copy the code

This class contains five main attributes: name, gender, city, hobby, and remarks. There are multiple hobbies, so they’re represented by arrays.

Create a form component

Use the Angular CLI command ng g component to generate a new component named UserForm:

ng g component components/userForm

Copy the code

Because template-driven forms reside in their own modules, you need to add The FormsModule to the application module’s imports array before using the forms. Make changes to app.module.ts:

import { FormsModule }   from '@angular/forms';



  imports: [

    BrowserModule,

    FormsModule

  ]

Copy the code

There are two changes

  1. The importFormsModule.
  2. theFormsModuleAdded to thengModuleThe decoratorimportsList, so that the application can access all features of template-driven forms, includingngModel.

As for the analysis of the form content, the official document is very detailed. Here, I only analyze the difficulties in this case, and you can read the official document for other details.

user-form.component.html is as follows:

<h2>Personnel registration system</h2>

<div class="container">

  <div [hidden] ="submitted">

    <form (ngSubmit) ="onSubmit()" #form="ngForm">

      <div class="form-group">

        <label for="name">name</label>

        <input class="form-control" id="name" type="text" required name="name" [(ngModel)] ="user.name" #name="ngModel">

        <span [hidden] ="name.valid || name.pristine" class="alert alert-danger">Name is required</span>

      </div>



      <div class="form-group">

        <label>Sex don't</label> &nbsp;

        <div class="radio-inline">

          <input type="radio" value="Male" name="sex" id="man" [(ngModel)] ="user.sex" > <label for="man">male</label>

        </div>

        <div class="radio-inline">

          <input type="radio" value="Female" name="sex" id="woman" [(ngModel)] ="user.sex" > <label for="woman">female</label>

        </div>

      </div>



      <div class="form-group">

        <label for="city">city</label>

        <select class="form-control" id="city" required name="city" [(ngModel)] ="user.city" #city="ngModel">

          <option *ngFor="let ct of cities" [value] ="ct">{{ct}}</option>

        </select>

        <span [hidden] ="city.valid || city.pristine" class="alert alert-danger">City is required</span>

      </div>



      <div class="form-group">

        <label for="hobby">Love is good</label>&nbsp;

        <span *ngFor="let item of user.hobbies; let key=index" class="checkbox-inline">

          <input type="checkbox" [id] ="'check'+key" [(ngModel)] ="item.status" [name] ="'check'+key"><label [for] ="'check'+key">{{item.title}}</label>

&nbsp; &nbsp;

        </span>

      </div>



      <div class="form-group">

        <label for="remark">For note</label>

        <textarea class="form-control" id="remark" type="text" required name="remark" [(ngModel)] ="user.remark" #remark="ngModel"></textarea>

        <span [hidden] ="remark.valid || remark.pristine" class="alert alert-danger">remark is required</span>

      </div>



      <button type="submit" class="btn btn-success" [disabled] =! "" form.valid">Submit</button>

      <button type="button" class="btn btn-default" (click) ="newUser(); form.reset()">New User</button>



    </form>

  </div>



  <div [hidden] =! "" submitted">

    <h2>You submitted the following:</h2>

    <div class="row">

      <div class="col-xs-3">name</div>

      <div class="col-xs-9">{{ user.name }}</div>

    </div>

    <div class="row">

      <div class="col-xs-3">Sex don't</div>

      <div class="col-xs-9">{{  user.sex }}</div>

    </div>

    <div class="row">

      <div class="col-xs-3">city</div>

      <div class="col-xs-9">{{  user.city }}</div>

    </div>

    <div class="row">

      <div class="col-xs-3">Love is good</div>

      <div class="col-xs-9">

        <span *ngFor="let item of user.hobbies">

          <span *ngIf="item.status == 1">{{item.title}}</span>&nbsp; &nbsp;

        </span>

      </div>

    </div>

    <div class="row">

      <div class="col-xs-3">For note</div>

      <div class="col-xs-9">{{  user.remark }}</div>

    </div>

    <br>

    <button class="btn btn-primary" (click) ="submitted=false">Edit</button>

  </div>

</div>

Copy the code

Compared with the case in the official document, the case in this paper adds the application of single select box and multiple select box, especially the multiple select box. Considering the two-way binding of data, the user. Hobbies property must be initialized.

user-form.component.ts is as follows:

import { Component, OnInit } from '@angular/core';

import { Uuser } from '.. /.. /model/uuser';



@Component({

  selector'app-user-form'.

  templateUrl'./user-form.component.html'.

  styleUrls: ['./user-form.component.css']

})

export class UserFormComponent implements OnInit {



  submitted = false;

  cities = ['Beijing'.'Shanghai'.'guangzhou'.'shenzhen'.'hangzhou'.'wuhan'.'chengdu'];

  hobbies = ['singing'.'dancing'.'running'.The 'fitness'.'swimming'];



  user = new Uuser(' '.'male'.this.cities[1], [], ' ');

  constructor() {}



  ngOnInit(): void {

    this.setHobbies();

  }



  // Each User object initializes the Hobby property, except that the status value defaults to 0, which is modified by the foreground check

  setHobbies() {

    // tslint:disable-next-line: prefer-for-of

    for (let i = 0; i < this.hobbies.length; i++) {

      this.user.hobbies.push(

        {

          titlethis.hobbies[i],

          status0

        }

      );

    }

  }



  onSubmit() {

    this.submitted = true;

  }



  newUser() {

    this.user = new Uuser(' '.' '.' '[],' ');

    this.setHobbies();

  }



}

Copy the code

Some changes have been made to the CSS style of the form to make it more visually appealing.

The first is styles.css, which introduces the Bootstrap style to optimize the overall frame display of the form.

@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css');

Copy the code

The second is user-form.com ponent. CSS

h2{

  text-align: center;

}

.ng-valid[required]..ng-valid.required  {

  border-left5px solid #42A948/* green */

}



.ng-invalid:not(form)  {

  border-left5px solid #a94442/* red */

}

Copy the code

You can add a colored vertical bar on the left side of the input box. When you enter valid content in the required field, the left side of the input box will turn green. Otherwise, it will be regarded as invalid and turn red.

Test page

To verify the above code, first go through the logical process.

Firstly, maintain a person’s basic information. Click the Submit button to Submit the form, which means jump to the page for viewing personnel information. Then click the Exit button to return to the page for maintaining personnel. If you submit the form again, you can jump to the personnel information viewing page.

During the test, it can be found that when the required items are not filled in, the Submit button is always gray, that is, it cannot be clicked to Submit. This is an effective verification of the whole form, which is also necessary in practical application.

One thing to note about gender checkboxes: Normally we set the default value of the checkbox to checked, but since two-way data binding is used in the current case, this property does not work, so we must set the default value of user.sex to make the checkbox default.

From the point of view of bidirectional data binding, it is impossible to add data to user.hobbies. The checkbox only changes the state value, so a setHobbies method will be added to user-form.component.ts file.

conclusion

This article optimizes the use of Angular forms, leveraging framework features to support data modification, validation, and more:

  • Angular HTML form template.
  • with@ComponentDecorator form component class.
  • By binding toNgForm.ngSubmitEvent property to handle form submission.
  • The template references variables, for example#form#name.
  • [(ngModel)]The syntax is used to implement two-way data binding.
  • nameAttributes are used for validation and tracking changes to form elements.
  • On a reference variable to the input controlvalidProperty that can be used to check whether the control is valid and to show/hide error messages.
  • By binding toNgFormThe effectiveness of state controlSubmitThe disabled state of the button.
  • Customize CSS classes to give users visual feedback on invalid controls.

reference

The official documentation