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

首頁 > 語言 > JavaScript > 正文

Angular 4.x中表單Reactive Forms詳解

2024-05-06 15:18:01
字體:
來源:轉載
供稿:網友

Angular 4.x 中有兩種表單:

Template-Driven Forms - 模板驅動式表單 (類似于 Angular 1.x 中的表單 ) Reactive Forms (Model-Driven Forms) - 響應式表單

Template-Driven Forms (模板驅動表單) ,我們之前的文章已經介紹過了,了解詳細信息,請查看 - Angular 4.x Template-Driven Forms 。

Contents

ngModule and reactive forms FormControl and FormGroup Implementing our FormGroup model Binding our FormGroup model Reactive submit Reactive error validation Simplifying with FormBuilder

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 reactive forms

在我們繼續深入介紹 reactive forms 表單前,我們必須在 @NgModule 中導入 @angular/forms 庫中的 ReactiveFormsModule:

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

友情提示:若使用 reactive forms,則導入 ReactiveFormsModule;若使用 template-driven 表單,則導入 FormsModule。

Reactive approach

我們將基于上面的定義的基礎表單,創建 SignupFormComponent :

signup-form.component.ts

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

這是一個基礎的組件,在我們實現上述功能前,我們需要先介紹 FormControl、FormGroup、FormBuilder 的概念和使用。

FormControl and FormGroup

我們先來介紹一下 FormControl 和 FormGroup 的概念:

1、FormControl - 它是一個為單個表單控件提供支持的類,可用于跟蹤控件的值和驗證狀態,此外還提供了一系列公共API。
使用示例:

ngOnInit() { this.myControl = new FormControl('Semlinker');}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 屯门区| 商都县| 云阳县| 盐源县| 五大连池市| 巧家县| 枣阳市| 池州市| 彰化县| 利津县| 敖汉旗| 万宁市| 奎屯市| 阳山县| 九江市| 张家川| 沅江市| 定西市| 白城市| 惠水县| 长治市| 商河县| 南安市| 古丈县| 九龙县| 沂源县| 德惠市| 阳春市| 藁城市| 个旧市| 通辽市| 黄浦区| 田东县| 巴林右旗| 和龙市| 临安市| 含山县| 江山市| 绥棱县| 西充县| 讷河市|