Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms In angular2

Bit confused about how to use Forms(template or modal driven froms) in the angular2 beta.

currently i am using modal driven forms but getting some error here is my form.html:

<form [ngFormModel]="demo">
        <input type="text"  [ngFormControl]="demo.controls['name']">
        <input type="text"  [ngFormControl]="demo.controls['batch']">
        <div> 
            <input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="true"> Active
            <input type="radio" [ngFormControl]="demo.controls['radio']" name="status" value="false">Inactive 
        </div>
        <div> 
            <input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="one" value="one"> one
            <input type="checkbox" [ngFormControl]="demo.controls['checkbox']" name="two" value="two">two 
        </div>
        <select [ngFormControl]="demo.controls['select']">
            <option value="one">Oone</option>
            <option value="two">two</option>
            <option value="three">three</option>
            <option value="four">four</option>
        </select>
        <button type="button" class="btn btn-primary btn-lg" data-dismiss="modal" (click)="demoSubmit(demo.value)">Done</button>
</form>

and form.ts file is here:

import {Component, View} from 'angular2/core';
import {FORM_DIRECTIVES, CORE_DIRECTIVES, FormBuilder, Control, ControlGroup} from 'angular2/common';
import {ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
    selectro: 'Form',
    templateUrl: 'src/components/form/form.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES],
})
export class FormDemo{
    demo:ControlGroup;
    constructor(fb:FormBuilder){
        console.log("Form Called");

        this.demo= fb.group({
            name: ["pardeep"],
            batch: [],
            checkbox: [],
            radio: [],
            select: []
        })
    }
    demoSubmit (){
        console.log(JSON.stringify(this.demo.value));
    }
}

so, my questions is:

  1. which form is best template or modal driven and why ?
  2. when to use ngControl and when to use ngModal ?

PS:- in this example i am unable to get the values of radio button and check-box selected am i doing something wrong, in this example i am modal driven form From here?

any good reference or example is welcome. thanks.

like image 796
Pardeep Jain Avatar asked Dec 18 '15 06:12

Pardeep Jain


2 Answers

I'm guessing that by ngModal you mean ngModel.

"1-which form is best template or modal driven and why ?"

from: http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

To create a new ControlGroup and Controls implicitly use:

ngForm and ngControl

To bind to an existing ControlGroup and Controls use:

ngFormModel and ngFormControl

Basically one is more convenient but gives you less control, personally I try to use template driven first because its more simple and less code, until it is not enough then I switch to model driven.

2- When to use ngControl and when to use ngModel ?

I don't know if you are mixing concepts here but ngControl and ngModel are not precisely meant to replace each other, ngModel handles the sync between input components and your domain/presentation model while ngControl handles the state of the form based on Validators, dirtiness of the input, etc, more geared towards giving feedback and allowing/stopping the user from submitting an unvalid form.

The ones that could replace each other are the one I mentioned previously in answer 1.

I hope that helps clarify a little bit?

As for the values of checkbox and radios, you only have ngFormControl's on them, add ngModel to map their values into your model. Once again quoting from the same page:

<input type="text" id="productNameInput" placeholder="Product Name" [ngFormControl]="myForm.find('productName')" [(ngModel)]="productName">

You can see that he is using both the ngFormControl and the ngModel.

like image 105
Langley Avatar answered Oct 27 '22 10:10

Langley


Got cleared some points related to FORMs in angular2 so posting as answer may help to someone !!

when to use ngControl and when to use ngModel ?

Basically we can ngControl for both to get values of forms as well as for validations but there are some probelms using this methods so best solution is according to me use ngModel for getting values of the form into your class and use ngControl for the validation purpose. there are default validators provide by angular to check validation we can create our custom one too as per need and can use in the validation (ngControl). if we are going to create model driven form i.e we have to create new control for every input by using new Control(). for the Control, control group and validation refer this best artical

http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

here is the basic example of using controls for the form:

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })

Here i have three inputs named name, password,select respectively. and corresponding i have mentioned their values and validators (default validation).

<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>

here is how we define ngControl to out HTML side.

Angular2 FORM with controls and validation.

After a lot searching i concluded that using ngModel is best to get values from form. by using same it is easier to clear to controls of the forms. and validations gets easy. and used ngControl for checking validations.

here is my working code for the form.

<form class="form-horizontal" id='myForm' role="form" [ngFormModel]="CreateGroup">

  <div class="col-md-7">
    Name: <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name'>
  </div>
  
  <div class="col-md-7">
    Password:   <input type="password" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password'>
  </div>
   
  <div class="col-md-7">
    <input type="radio" name='type' (click)='demoInfo.radio="Btech"' [checked]="'Btech' === demoInfo.radio">Btech
    <input type="radio" name='type' (click)='demoInfo.radio="Mtech"' [checked]="'Mtech' === demoInfo.radio">Mtech
  </div>
  
  <div class="col-md-7">
    <select #selectOption (change)='demoInfo.select=selectOption.value' class='form-control' ngControl='select'>
      <option> select</option>
      <option value='One' [selected]="demoInfo.select==='One'">One Value</option>
      <option value='Two' [selected]="demoInfo.select==='Two'">two Value</option>
      <option value='Three' [selected]="demoInfo.select==='Three'">Three Value</option>
    </select>
  </div>
</form>
<br>
<div class='text-center'>
  <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Create</button>
</div>

and code for the class side is here...

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

class DemoInfo{
  name:string;
  password: string;
  radio: any;
  select: any;
}
@Component({
    selector: 'my-app',
    templateUrl: 'mytemplate.html',
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES] 
})
export class AppComponent { 
  CreateGroup: FormBuilder;
  demoInfo: DemoInfo;
  constructor(fb: FormBuilder){
    this.demoInfo= new DemoInfo(); 
    
    this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })
  }
  addNewGroup(demoInfo:demoInfo) {
    console.log(demoInfo, 'whole object');
    this.demoInfo= new DemoInfo();
  }
}

refer this for working plunkr here .

like image 35
Pardeep Jain Avatar answered Oct 27 '22 10:10

Pardeep Jain