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

De Basef
Ir para: navegação, pesquisa
 
(4 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 29: Linha 29:
  
 
<source lang="javascript">
 
<source lang="javascript">
import { FormGroup, FormBuilder } from '@angular/forms';
+
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
  
 
export class MyComponent {
 
export class MyComponent {
Linha 36: Linha 36:
 
     constructor(private fb: FormBuilder) {
 
     constructor(private fb: FormBuilder) {
 
         this.myForm = fb.group({
 
         this.myForm = fb.group({
             'field1': '',
+
             'field1': ['', Validators.required],
             'field2': ''
+
             'field2': ['']
 
         });
 
         });
 
     }
 
     }
Linha 48: Linha 48:
  
 
<source lang="xml">
 
<source lang="xml">
 +
 
<form [formGroup]="myForm">
 
<form [formGroup]="myForm">
 
     <input type="text" formControlName="field1" />
 
     <input type="text" formControlName="field1" />
Linha 54: Linha 55:
 
</source>
 
</source>
  
or
+
[[Category: Angular]]
 
+
<source lang="xml">
+
<form [formGroup]="myForm">
+
    <input type="text" [formControl]="myForm.controls['field1']" />
+
    <input type="text" [formControl]="myForm.controls['field2']" />
+
</form>
+
</source>
+

Edição atual tal como às 10h39min de 27 de janeiro de 2020

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:

<form [formGroup]="myForm">
    <input type="text" formControlName="field1" />
    <input type="text" formControlName="field2" />
</form>