search
HomeWeb Front-endJS TutorialHow to operate Angular template-driven forms

This time I will show you how to operate the Angular template-driven form, and what are the precautions when operating the Angular template-driven form. The following is a practical case, let's take a look.

I won’t go into details about the importance of forms. Angular supports two-way data binding, verification, status management, etc. of forms. Let’s summarize.

Get user input

<p>
 </p><h1 id="Angular表单">Angular表单</h1>
 
  

       

  

      

  

      

 

If you have the above simple form, regardless of its advantages or disadvantages, what are the ways to obtain the form data? Let’s first look at two simple and crude

1) Event $event methods

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


testInput ( _input: any) {
  console.dir(_input);
}

After triggering submit, check the results. It looks very familiar. It is an event in the traditional method. Needless to say, the target is the form element, and then locate the input sub-element and obtain the value respectively.

In order to obtain 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. So this method is not advisable

2) Template reference variables

You can use template reference variables (#var) in Angular to reference DOM elements/Angular components/instructions. Usually the template reference variable represents the declared element. Of course, the pointer can also be modified to represent Angular instructions (such as the ngForm instructions and ngModel instructions used later).

// 模版引用变量代表Form元素
// 模版引用变量代表ngForm指令

You can see the difference from the picture 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 (have you entered it? Has the verification passed? etc.), which will be explained in detail later

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

 
  

       

Note: Template referenceThe scope of the variable is the entire template, so in the same template, there cannot be the same name Template reference variables

These two ways of obtaining form data are just for understanding, because Angular provides two better ways to build forms---template-driven forms and model-driven forms

Template driven form

As the name suggests, it uses HTML template 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. Template-driven forms use [(ngModel)] syntax for two-way data binding. It is very simple to bind form data to the model. Note that when using [ngModel] in a form, you must define the name attribute, because when Angular processes the form, it will create some FormControl to track the value and status of a single form control, and the name attribute of the form control is the key value, so it must To specify the name attribute. (This should be regarded as pointing out two scientific ways to obtain form data: [ngModel] syntax binding and obtaining through formControl’s API)

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

3. Use the ngModel directive to monitor the status of a single form control, and also use specific Angular css to update the control style. We When different states can be controlled through these classes, the display of form controls

4,Form validationcan 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;

还可以自定义验证器,因为模版驱动表单不直接访问FormControl实例,所以需要把自定义的验证器用指令包装。

通过以下栗子来展示模版驱动表单简单使用

<!-- 模版引用变量指向ngForm指令 -->
 
  

                      

       

    用户名不能为空!     用户名只能包含英文或数字!   

  

      

  

   密码不能为空!   

  

          

 

通过Angular css 自动添加的class来控制表单样式

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

查看下效果,表单校验、样式反馈、按钮状态管理、数据获取都很方便。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

优化vue项目步骤详解

怎样使用Node.js内Koa实现JWT用户认证

The above is the detailed content of How to operate Angular template-driven forms. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
聊聊Angular中的元数据(Metadata)和装饰器(Decorator)聊聊Angular中的元数据(Metadata)和装饰器(Decorator)Feb 28, 2022 am 11:10 AM

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

浅析angular中怎么使用monaco-editor浅析angular中怎么使用monaco-editorOct 17, 2022 pm 08:04 PM

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

Angular + NG-ZORRO快速开发一个后台系统Angular + NG-ZORRO快速开发一个后台系统Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

聊聊Angular Route中怎么提前获取数据聊聊Angular Route中怎么提前获取数据Jul 13, 2022 pm 08:00 PM

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools