首页 > 代码库 > [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