2016.06.16

learning list

  • Angular form
    1. 隐式构建表单对象
    2. 显式构建表单对象
    3. 添加验证器
    4. 自定义验证器
import { Component } from '@angular/core';
import { FormsModule, ReactiveFormsModule} from '@angular/forms';

// FormsModule 下提供了 ngForm ngModel指令
// ReactiveModule 下提供了 formControl NgFormGroup 指令
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
  ],
  bootstrap: [ AppComponent]
})
export class AppModule {...}


// 使用:显示、隐试
// 隐试 ngForm ngModel 隐式构建FormContro,FormGroup类型的表单对象
@Component({
  selector: 'demo-form',
  template: `
    <form #f=ngForm>
      <input type="text" name="sku" ngModel>
      <button (ngSubmit)="onSubmit(f.value)"></button>
    </form>`
})
export class DemoForm {
  onSubmit(value: any) {
    console.log('you have submit: ', value);
  }
}

// 显式 - FormBuilder 帮助更多定制化地来构建表单对象
import { FormGroup, FormBuilder } from '@angular/forms'
@Component({
  template: `
    <form [formGroup]="myForm">
      <input type="text" name="sku" [formControl]="myForm.controls['sku']">
      <button (ngSubmit)="onSubmit(myForm.value)"></button>
    </form>`
})
class DemoFormBuilder {
  myForm: FormGroup
  constructor (fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validater]
    })
  }
  onSubmit(value: any): void {
    console.log('you have submit: ', value);
  }
}

// 添加验证
myForm.controls['sku', Validators.required]

results matching ""

    No results matching ""