[Angular2 Form] Reactive Form, FormBuilder

泄露秘密 提交于 2020-02-28 10:46:35

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
      ],

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!