Mudanças entre as edições de "Model Driven Forms (Reactive forms) in Angular2"

De Basef
Ir para: navegação, pesquisa
(3) In your template:)
Linha 47: Linha 47:
 
These are similar to ngModel of Angular1:
 
These are similar to ngModel of Angular1:
  
 +
<source lang="xml">
 
<source lang="xml">
 
<source lang="xml">
 
<form [formGroup]="myForm">
 
<form [formGroup]="myForm">
     <input type="text" formControlName="field1" />
+
     <input type="text" [formControl]="myForm.controls['field1']" />
     <input type="text" formControlName="field2" />
+
     <input type="text" [formControl]="myForm.controls['field2']" />
 
</form>
 
</form>
 
</source>
 
</source>
  
or
 
  
<source lang="xml">
+
or
 
<form [formGroup]="myForm">
 
<form [formGroup]="myForm">
     <input type="text" [formControl]="myForm.controls['field1']" />
+
     <input type="text" formControlName="field1" />
     <input type="text" [formControl]="myForm.controls['field2']" />
+
     <input type="text" formControlName="field2" />
 
</form>
 
</form>
 
</source>
 
</source>
 +
 +
[[Category: AngularJS2]]

Edição das 15h06min de 23 de abril de 2018

A complete guide to reactive forms: Thoughtram - Model Driven Forms in Angular 2

1) In your Module:

import { ReactiveFormsModule } from '@angular/forms';

Add `ReactiveFormsModule` to `imports` section.

2) In your Component:

import { FormGroup, FormControl } from '@angular/forms';
 
export class MyComponent {
    myForm: FormGroup;
 
    constructor() {
        this.myForm = new FormGroup({
            field1: new FormControl(),
            field2: new FormControl()
        });
    }
}

or

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
 
export class MyComponent {
    myForm: FormGroup;
 
    constructor(private fb: FormBuilder) {
        this.myForm = fb.group({
            'field1': ['', Validators.required],
            'field2': ['']
        });
    }
}

3) In your template:

These are similar to ngModel of Angular1:

<source lang="xml">
<form [formGroup]="myForm">
    <input type="text" [formControl]="myForm.controls['field1']" />
    <input type="text" [formControl]="myForm.controls['field2']" />
</form>


or <form [formGroup]="myForm">

   <input type="text" formControlName="field1" />
   <input type="text" formControlName="field2" />

</form> </source>