码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular2 Form] Reactive Form, FormBuilder

时间:2016-10-26 07:26:29      阅读:428      评论:0      收藏:0      [点我收藏+]

标签:val   field   for   value   code   struct   log   which   ova   

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

标签:val   field   for   value   code   struct   log   which   ova   

原文地址:http://www.cnblogs.com/Answer1215/p/5998956.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!