国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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 輸入框的值。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 大化| 丹阳市| 贺州市| 呼玛县| 宝应县| 腾冲县| 中宁县| 桑日县| 桐柏县| 嵊泗县| 饶平县| 剑河县| 鄢陵县| 石阡县| 三穗县| 平江县| 九龙县| 青川县| 顺义区| 农安县| 秭归县| 上林县| 麻阳| 张家界市| 盐津县| 沈丘县| 阿勒泰市| 抚松县| 宜城市| 南阳市| 凤城市| 寻乌县| 莫力| 松桃| 嘉兴市| 安化县| 加查县| 育儿| 丹凤县| 上高县| 兴隆县|