Angular usage summary --- template-driven form

  Not to mention the importance of forms, Angular supports two-way data binding of forms, validation, state management, etc., to sum up.

Get user input

 1 <div class="container-fluid login-page">
 2   <h1>Angular表单</h1>
 3   <form class="login-area">
 4     <div class="form-group">
 5         <input class="form-control" type="text" name="name" id="login-name" placeholder="请输入登录帐号">
 6     </div>
 7     <div class="form-group">
 8       <input class="form-control"type="password" name="pwd" id="login-pwd" placeholder="请输入登录密码">
 9     </div>
10     <div class="form-group">
11       <button type="submit" class="btn btn-block btn-success">登录</button>
12     </div>
13   </form>
14 </div>

  If there is the above simple form, regardless of the pros and cons, what are the ways to get the form data? Let's look at two simple and rude

  1) The way of event $event

  When listening to an event, pass the entire event payload $event to the event handler, which will carry various information about the triggering element. Here we listen to the submit event of the form element, pass the information of the entire form to the processing function, and print it out

<form class="login-area"  (submit)="testInput($event)">
testInput ( _input: any) {
    console.dir(_input);
}

  After triggering submit, view the results. It is very familiar. It is the event in the traditional method. Needless to say, the target is the form element, and then locate the input sub-element, and get the value separately.

  In order to get the value of the input, we pass a lot of useless information, the processing function does not care about the position, attributes, etc. of the element at all, it only needs the value value. So this way is not advisable

  2) Template reference variable

  In Angular, template to reference DOM elements/Angular components/directives. Usually the template reference variable is the element that represents the declaration, of course, it can also be modified to point to, and can represent Angular directives (such as the ngForm directive and the ngModel directive that will be used later).

// The template reference variable represents the Form element
<form class="login-area" #test  (submit)="testInput(test)">

// The template reference variable represents the ngForm directive
 <form class="login-area" #test="ngForm"(submit)="testInput(test)">

  You can see the difference from the figure below. The first one is the same as $event.target, which is a DOM element; the second one is the ngForm instruction, which can track the value and status of each control (is it input? Is the verification passed? etc. ), which will be described in detail later

  So when we directly use the template reference variable to refer to the input element, we can directly pass the value of the input element in the template without passing the entire element information. This method is not good either, it must be triggered by an event before it can be delivered

  <form class="login-area" (submit)="testInput(test.value)">
    <div class="form-group">
        <input class="form-control" #test  type="text" name="name" id="login-name" placeholder="请输入登录帐号">
    </div>

  Note: The scope of template reference variables is the entire template, so in the same template, there cannot be template reference variables with the same name

  These two ways to get form data are just to understand, because Angular provides two better ways to build forms---template-driven forms and model-driven forms

Template Driven Forms

  As the name suggests, it uses HTML templates + Form Professional Instructions to build forms. To use template-driven forms, remember to import FormsModule in the application module first. Explain the following points:

  1. The template-driven form uses the [(ngModel)] syntax for two-way data binding, which is very simple to bind the form data to the model. Note that when using [ngModel] in a form, the name attribute must be defined , because when Angular processes the form, it will create some FormControls to track the value and state of a single form control , and the form control name attribute is the key value , so it must be To specify the name attribute. (This should be regarded as pointing out two scientific ways of obtaining form data: [ngModel] syntax binding and obtaining through formControl's Api)

  2. Use the ngForm directive to monitor the validity of the entire form (valid attribute) . Angular will automatically create and add the ngForm directive for the form form, you can use it directly

  3. Use the ngModel directive to monitor the state of a single form control, and use specific Angular css to update the control style.  We can use these classes to control the display of form controls in different states.

  

  4. Form validation can use HTML native form validation attributes (required , pattern , max , min , etc.), when validation errors occur, the errors attribute mentioned in 3 will have corresponding error items;

     You can also customize the validator, because the template-driven form does not directly access the FormControl instance, so you need to wrap the custom validator with a directive.

  Use the following chestnuts to demonstrate the simple use of template-driven forms

        <!-- The template reference variable points to the ngForm directive --> 
  < form class ="login-area" #testform ="ngForm" (submit) ="testInput()" > 
    < div class ="form-group" > 
        <! -- ngModel binding data --> 
        <!-- required and pattern specify validation rules --> 
        <!-- template reference variable points to ngModel directive --> 
        < input class ="form-control" type ="text" name = "name" id = "login-name" placeholder = "Please enter the login account"
               [(ngModel)] = "user.name"   
               required
               pattern ="[0-9A-z]+" 
               #nameinput = "ngModel" 
               > 
    </ div > 
        <!-- Control whether to display the error description and what kind of error description to display through the state of the form control --> 
    < div class = "form-group" *ngIf ="nameinput.touched&&nameinput.invalid" > 
        < span class ="error-info" *ngIf ="nameinput.errors?.required" > Username cannot be empty! </ span > 
        < span class ="error-info" *ngIf ="nameinput.errors?.pattern" > Username can only contain English or numbers! </ span >
    </div>
    <div class="form-group">
      <input class="form-control" type="password" name="pwd" id="login-pwd" placeholder="请输入登录密码"
             [(ngModel)] = "user.pwd"
             required
             #pwdinput = "ngModel" > 
    </ div > 
    < div class ="form-group" *ngIf ="pwdinput.touched&&pwdinput.invalid" > 
      < span class ="error-info" *ngIf ="pwdinput.errors?.required " > Password cannot be empty! </ span > 
    </ div > 
    < div class = "form-group" > 
      <!-- Control whether the button is available through the state of the form --> 
      < button type = "submit"="testform.invalid">登录</button>
    </div>
  </form>

  Control form styles with classes automatically added by Angular css   

input.ng-invalid.ng-touched {
        border: 2px solid red;
 }

  View the effect, form validation, style feedback, button state management, data acquisition are very convenient.

  As for how to customize the validator, it will be explained together with the custom validator of the model-driven form, that is the next article; if there are any shortcomings in the essay, you are welcome to correct me...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325282574&siteId=291194637