Angular 从入坑到挖坑 - 表单控件概览
2020/3/5 11:01:36
本文主要是介绍Angular 从入坑到挖坑 - 表单控件概览,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Overview
angular 入坑记录的笔记第三篇,介绍 angular 中表单控件的相关概念,了解如何在 angular 中创建一个表单,以及如何针对表单控件进行数据校验。
对应官方文档地址:
配套代码地址:angular-practice/src/forms-overview
Contents
Knowledge Graph
![思维导图](/upload/202003/05/202003051101343529.png)
Step by Step
表单简介
用来处理用户的输入,通过从视图中捕获用户的输入事件、验证用户输入的是否满足条件,从而创建出表单模型修改组件中的数据模型,达到获取用户输入数据的功能
模板驱动表单 | 响应式表单 | |
---|---|---|
建立表单 | 由组件隐式的创建表单控件实例 | 在组件类中进行显示的创建控件实例 |
表单验证 | 指令 | 函数 |
在表单数据发生变更时,模板驱动表单通过修改 ngModel 绑定的数据模型来完成数据更新,而响应式表单在表单数据发生变更时,FormControl 实例会返回一个新的数据模型,而不是直接修改原来的数据模型
模板驱动表单
通过使用表单的专属指令(例如 ngModel 进行双向数据绑定)将数据值和一些对于用户的行为约束(某个字段必须填啊、某个字段长度超过了长度限制啊)绑定到组件的模板中,从而完成与用户的交互
模板驱动表单的双向数据绑定
在根模块中引入 FormsModule,并添加到根模块的 imports 数组中
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // 引入 FormsModule import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { TemplateDrivenFormsComponent } from './template-driven-forms/template-driven-forms.component'; @NgModule({ declarations: [ AppComponent, ReactiveFormsComponent, DynamicFormsComponent, TemplateDrivenFormsComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule // 添加到应用模块中 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } 复制代码
新建一个类文件,用来承载组件与模板之间进行双向数据绑定的数据信息
ng g class classes/hero 复制代码
export class Hero { /** * ctor * @param name 姓名 * @param age 年纪 * @param gender 性别 * @param location 住址 */ constructor(public name: string, public age: number, public gender: string, public location: string) { } } 复制代码
在组件的模板中创建承载数据的表单信息,并使用 ngModel 完成组件与模板之间的数据双向绑定
<form> <div class="form-group"> <label for="name">姓名:</label> <input type="text" name="name" id="name" [(ngModel)]="hero.name" class="form-control" autocomplete="off" required minlength="4"> </div> <div class="form-group"> <label for="age">年龄:</label> <input type="number" name="age" id=
这篇关于Angular 从入坑到挖坑 - 表单控件概览的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)