Forms In angular2

后端 未结 5 2031
耶瑟儿~
耶瑟儿~ 2020-12-03 13:01

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 f

相关标签:
5条回答
  • 2020-12-03 13:06

    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.

    0 讨论(0)
  • 2020-12-03 13:12

    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

    0 讨论(0)
  • 2020-12-03 13:16

    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:

    • https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol

    • https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2

    Live Demo for the same here

    Working Demo for angular2 Forms

    0 讨论(0)
  • 2020-12-03 13:21

    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 .

    0 讨论(0)
  • 2020-12-03 13:29

    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
    }
    
    0 讨论(0)
提交回复
热议问题