Angular Reactive Forms (minimal example)

Reactive or not reactive that is the question. 

Angular offers two form-building technologies: reactive forms and template-driven forms. One advantage of Angular reactive forms is that value and validity updates are always synchronous and under your control. You don’t need to bother with the timing issues that sometimes plague a template-driven form. Moreover reactive forms can be easier to unit test.

Neither is “better”. They’re two different architectural paradigms, with their own strengths and weaknesses. Choose the approach that works best for you. You may decide to use both in the same application.

Reactive forms have lots of features to learn an documentation can be often overwhelming so here is minimal example how to use them:

Lets start with hero-detail.component.ts, all the magic happens in createForm() method:

...
@Component({
selector: 'hero-detail',
templateUrl: './hero-detail.component.html'
})
export class HeroDetailComponent implements OnChanges {
heroForm: FormGroup;
...
constructor(
private fb: FormBuilder,
this.createForm();
...
}
createForm() {
this.heroForm = this.fb.group({
name: new FormControl("", [
Validators.required,
Validators.minLength(4)
]),
power: '',
sidekick: ''
});
}
...
}

Then we have here hero-detail.component.html with our form and all the validation warnings hidden divs:

...
<form [formGroup]="heroForm" (ngSubmit)="onSubmit()" novalidate>
<div style="margin-bottom: 1em">
<button type="submit"
[disabled]="heroForm.pristine || name.invalid" class="btn btn-success">Save</button> &nbsp;
<button type="reset" (click)="revert()"
[disabled]="heroForm.pristine" class="btn btn-danger">Clear</button>
</div>
<!-- Hero Detail Controls -->
<div class="form-group">
<label class="center-block">Name:
<input id="name" class="form-control" formControlName="name" required >
</label>
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
</div>
...
</form>

And that’s pretty all. Last thing is not to forgot import ReactiveFormsModule in app.module.ts:

...
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule // <-- #2 add to @NgModule imports
],
...
})
...

All examples are taken from official Angular documentation and are condensated to create minimal example.

Buy me a coffeeOut of coffee 😱, please help!