Sunday, 1 May 2016

Angular Js - Lesson 9 - Forms_7 - two way data binding with ngModel

Angular Js 2 - ngModel - Two way data binding


Angular 2 is built to generally have one-way data flow i.e., top-down. However, in forms, it is easier to use a two-way data binding.



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


@Component({
  selector: 'demo-form-ng-model',
  directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: with ng-model</h2>
    <div class="ui info message">
      The product name is: {{productName}}
    </div>
    <form [ngFormModel]="myForm"
          (ngSubmit)="onSubmit(myForm.value)"
          class="ui form">
      <div class="field">
        <label for="productNameInput">Product Name</label>
        <input type="text"
               id="productNameInput"
               placeholder="Product Name"
               <!--
                   we’re still using ngFormControl to specify that this input
                    should be bound to the Control on our form. We do this
                    because ngModel is only binding the input to the instance
                    variable productName - the Control is completely separate. But because
                    we still want to validate this value and submit it as part
                    of the form, we keep the ngFormControl directive.
               -->
               [ngFormControl]="myForm.find('productName')"
               <!--
                   we’re using both the input [] brackets and the output ()
                   parenthesis. It’s an indication of the two-way bind.
               -->
               [(ngModel)]="productName">
      </div>
      <div *ngIf="!myForm.valid"
        class="ui error message">Form is invalid</div>
      <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})


export class DemoFormNgModel {
  myForm: ControlGroup;
  productName: string;
  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'productName':  ['', Validators.required]
    });
  }
  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

//---------------------------------------------------------------------------------------------------------

No comments:

Post a Comment