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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft