Thursday, 28 April 2016

Angular Js - Lesson 9 - Forms_2

Angualr Js - Forms part 2 - using ngFormmodel and ngFormControl

To create a new ControlGroup and Controls implicitly use:
ngForm and ngControl.

To bind an already existing ControlGroup and Controls use ngFormModel and ngFormControl.



import { Component } from 'angular2/core';
import {
  FORM_DIRECTIVES,
  FormBuilder,
  ControlGroup
} from 'angular2/common';

@Component({
  selector: 'demo-form-sku-builder',
  directives: [FORM_DIRECTIVES],
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <!--
    The component ngForm is applied for us automatically when we use FORM_DIRECTIVES
    and this ngForm creates its own ControlGroup. But here we do not want to use any
    outside ControlGroup. Instead we want to use our instance varibale myForm which
    we created with our FormBuilder. To do this Angular gives us another directive
    that can be used when we have an existing ControlGroup. This directive is called
    ngFormModel. In the line <form [ngFormModel]="myForm" we are telling Angular
    that we want to use myForm as the ControlGroup for this form.
    -->
    <form [ngFormModel]="myForm"
          (ngSubmit)="onSubmit(myForm.value)"
          class="ui form">

      <div class="field">
        <label for="skuInput">SKU</label>
        <input type="text"
               id="skuInput"
               placeholder="SKU"
               <!-- When we want to bind an existing control to an input we use NgFormControl. -->
               [ngFormControl]="myForm.controls['sku']">
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {
  myForm: ControlGroup;
  /* During injection an instance of FormBuilder will be created
  and we assign that instance to the local variable fb in the line below.
   */
  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      /* We create a ControlGroup by calling method fb.group() which
      takes an object of key-value paris that specify the controls in this group.
       */
      'sku': ['ABC123']
      /* We are setting up one control sku and also setting its default value to ABC123.
      We are using an array in the line above so that we could later on
      add more configuration options here.
       */
    });
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

/***********************************************************************/


No comments:

Post a Comment