首页 > 代码库 > [Angular2 Form] Reactive Form, FormBuilder
[Angular2 Form] Reactive Form, FormBuilder
Import module:
import { NgModule } from ‘@angular/core‘;import { CommonModule } from ‘@angular/common‘;import { MessageComponent } from ‘./message.component‘;import messageRoutes from ‘./message.routes‘;import {FormsModule, ReactiveFormsModule} from "@angular/forms";@NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule, messageRoutes ], declarations: [MessageComponent]})export default class MessageModule { }
Define the html:
<form [formGroup]="reactiveForm" novalidate autocomplete="off"> <div class="form-field"> <label>Title:</label> <input formControlName="title"> </div> <div class="form-field"> <label>Description:</label> <input formControlName="description"> </div> <div class="form-field"> <button type="submit">Submit</button> </div></form>
ts:
reactiveForm: FormGroup;
constructor(fb: FormBuilder) { this.reactiveForm = fb.group({ title: [ ‘Title‘, [ Validators.required, Validators.minLength(3) ] ], description: [ ‘Description‘, [Validators.required] ] }) }}
group() function take an object param, each object stands for a field in template, which refer to ‘formControlName‘.
// title <-- formControlName="title" title: [ ‘Title‘, // <-- Default value [ Validators.required, Validators.minLength(3) ] // <-- Validations ],
[Angular2 Form] Reactive Form, FormBuilder
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。