6

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.

3

5 Answers 5

7

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.

3
  • amm i have already go through the link for refer. you provided ...secondly will you provide any plnkr for the example ? Jan 10, 2016 at 18:07
  • You can create one or a CodePen where it fails if you want, and I'll show you how to fix it there.
    – Langley
    Jan 10, 2016 at 18:27
  • hehe i am bit lazzy in all that things still ill inform you when i created one using your method. by the way thanx Jan 11, 2016 at 4:37
6

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 .

2
2

Try using new RadioButtonState(boolean, string) in your formbuilder.

ex.

Template:

<form [ngFormModel]="form" (ngSubmit)="doIt()">
    <h3>DisOrDat</h3>
    <hr />              
    <p>Choose</p>
    <div ngControlGroup="disOrDat">
        <div class="radio">
            <label>
                <input type="radio" name="choose" value="dis" ngControl="dis">Dis                                   
            </label>
            <label>
                <input type="radio" name="choose" value="dat" ngControl="dat">Dat
            </label>
        </div>
    </div>    
</form>

Component

// create the form as a colleciton of Controls
this.form = formBuilder.group({
    disOrDat: formBuilder.group(
        {
            dis: [new RadioButtonState(true, 'dis')],
            dat: [new RadioButtonState(false, 'dat')]
        }, 
        { 
            validator: this.disOrDatValidator 
        }
    )
});

disOrDatValidator(group: ControlGroup) { 
    /* tslint:disable:no-string-literal */
    if (group.controls['dis'].value !== group.controls['dat'].value) {
    /* tsslint:enable:no-string-literal */    
        return false;
    }

    // return null means validation passed
    return null;
}  

doIt() {
    // handle form submit
}
2
  • will you please provide any plnkr for the same ? Feb 25, 2016 at 6:07
  • thanx for the answer but i am looking for the values using ngModel. Feb 27, 2016 at 18:33
1

UPDATED - ANGULAR2 RC4 FORMS

(So many changes are there in new forms so posting as new answer)

After the release of angular2 RC Forms there are lot of changes have been made in angular2 forms. there are some of them are major breaking changes some of them are negligible, here are some key points for using angular2 forms.

Basically there are two ways to build forms in Angular 2, namely template-driven and model-driven. basic structure for using forms are as follows:-

  • run npm install @angular/forms --save
  • configure bootstrap method for your app as following:

    bootstrap(AppComponent, [
      disableDeprecatedForms(), // disable deprecated forms
      provideForms(), // enable new forms module
    ]);
    
  • use REACTIVE_FORM_DIRECTIVES to component directives to use forms functionality.

  • create Form variable of type FormGroup
  • Use Validators for validatiion purpose.

apart from this FormBuilder is not a mandatory to building model driven form, but it simplify the syntax. there are three basic syntax/method provided by formbuilder are:

  • group: construct a new form group.
  • array: construct a new form array.
  • control: construct a new form control.

These are the basic steps to use forms in angular2 RC.

Usefull resources for angular2 forms:

Live Demo for the same here

Working Demo for angular2 Forms

-2

My choice is using ngFormModel and ngControl, because we can collect form data more easily and can do validation ,etc.

See my angular2-seeds project for more detail

5
  • unable to start form.ts. i have to change in the gulpfile right ? Dec 27, 2015 at 16:19
  • and also i want to get value of radioButton and checkbox which is not mentioned in your repo. i am totaly confused how to get the value of radio and checkbox using ngControl. hope you will help me Dec 27, 2015 at 16:29
  • 1
    You've confused the concepts b/t ngFormModel and template based forms. You've used 'required' in your template but that should not be used if you are using ngFormModel and Controls. FWIW I'm still looking for how to properly do radio buttons as well...
    – JimB
    Feb 24, 2016 at 13:57
  • I think the only people who know how to use radio buttons are those who wrote angular... and they don't have time to explain to us mortals how it is supposed to work
    – Greg Woods
    Mar 11, 2016 at 17:10
  • https://github.com/pleerock/ng2-radio-group may help you.
    – flyingzl
    Jun 4, 2016 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.