首页 > 语言 > JavaScript > 正文

Angular.js 4.x中表单Template-Driven Forms详解

2024-05-06 15:17:58
字体:
来源:转载
供稿:网友

Angular 4.x 中有两种表单:

Template-Driven Forms - 模板驱动式表单 (类似于 Angular 1.x 中的表单 ) Reactive Forms - 响应式表单

本文主要介绍 Template-Driven Forms (模板驱动式表单) ,将涉及 ngForm、ngModel、ngModelGroup、表单提交事件、表单验证和异常信息输出等内容。

Contents

ngModule and template-driven forms Binding ngForm and ngModel ngModel,[ngModel] and [(ngModel)] ngModels and ngModelGroup Template-driven submit Template-driven error validation

Form base and interface

Form base

<form novalidate> <label> <span>Full name</span> <input type="text" name="name" placeholder="Your full name"> </label> <div> <label> <span>Email address</span> <input type="email" name="email" placeholder="Your email address"> </label> <label> <span>Confirm address</span> <input type="email" name="confirm" placeholder="Confirm your email address"> </label> </div> <button type="submit">Sign up</button></form>

接下来我们要实现的功能如下:

绑定 name、email、confirm 输入框的值 为所有输入框添加表单验证功能 显示验证异常信息 表单验证失败时,不允许进行表单提交 表单提交功能

User interface

// signup.interface.tsexport interface User { name: string; account: { email: string; confirm: string; }}

ngModule and template-driven forms

在我们继续深入介绍 template-driven 表单前,我们必须在 @NgModule 中导入 @angular/forms 库中的 FormModule:

import { FormsModule } from '@angular/forms';@NgModule({ imports: [ ..., FormsModule ], declarations: [...], bootstrap: [...]})export class AppModule {}

友情提示:若使用 template-driven 表单,则导入 FormsModule;若使用 reactive forms,则导入 ReactiveFormsModule。

Template-driven approach

使用模板驱动的表单,我们基本上可以将组件类留空,直到我们需要读取/写入值 (例如提交和设置初始值)。我们将基于上面的定义的基础表单,创建 SignupFormComponent :

signup-form.component.ts

import { Component } from '@angular/core';@Component({ selector: 'signup-form', template: ` <form novalidate>...</form> `})export class SignupFormComponent { constructor() {}}

这是一个很基础的组件,接下来我们导入之前定义的 User 接口,具体如下:

import { User } from './signup.interface';@Component({...})export class SignupFormComponent { public user: User = { name: '', account: { email: '', confirm: '' } };}

初始化 SignupFormComponent 组件类中的用户模型后,我们开始实现第一个功能点:即绑定 name、email、confirm 输入框的值。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选