Member-only story
Introduction to Angular Reactive Forms
Angular is a popular front-end framework made by Google. Like other popular front-end frameworks, it uses a component-based architecture to structure apps.
In this article, we’ll look at the basics of creating reactive forms with Angular.
Reactive Forms
Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time. Each change returns a new state, which maintains the integrity of the model between changes.
It’s also easier to test because the data is consistent and predictable.
We can create a Reactive form as follows:
app.module.ts
:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveFormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
:
import { Component } from "@angular/core";
import { FormControl } from "@angular/forms";@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
nameControl = new FormControl("");
}
app.component.html
:
<input type="text" [formControl]="nameControl" />
<p>{{ nameControl.value }}</p>
In the code above, we imported the ReactiveFormsModule
in app.module.ts
.
Then in AppComponent
, we added a FormControl
called nameControl
.
Then we connect our input element to nameControl
by using the formControl
property.
To display the value we typed in, we reference the nameControl
‘s value
property as we did with the p element.
Replacing a Form Control Value
We can call the setValue
method on a FormControl
to replace the value of it.
For example, we can write the following code: