0
0
Angularframework~5 mins

FormControl basics in Angular

Choose your learning style9 modes available
Introduction

FormControl helps you manage and track the value and status of a single form input in Angular. It makes handling user input easier and organized.

When you want to track the value of a single input field like a text box or checkbox.
When you need to validate user input and show errors.
When you want to react to changes in an input field immediately.
When building simple forms without grouping multiple controls.
When you want to programmatically set or reset input values.
Syntax
Angular
const control = new FormControl(initialValue, validators);

initialValue is the starting value of the input (can be empty).

validators are optional rules to check input correctness.

Examples
Creates a FormControl with an empty string as the initial value.
Angular
const nameControl = new FormControl('');
Starts the control with the number 18 as the value.
Angular
const ageControl = new FormControl(18);
Creates a control that requires a value (cannot be empty).
Angular
const emailControl = new FormControl('', Validators.required);
Control with two validators: must not be empty and at least 6 characters.
Angular
const passwordControl = new FormControl('', [Validators.required, Validators.minLength(6)]);
Sample Program

This Angular component creates a FormControl for a username input. It requires the username to be filled. If the user touches the input and leaves it empty, an error message shows. The current input value is displayed below.

Angular
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-simple-input',
  template: `
    <label for="username">Username:</label>
    <input id="username" [formControl]="usernameControl" aria-describedby="error" />
    <div *ngIf="usernameControl.invalid && usernameControl.touched" id="error" style="color: red;">
      Username is required.
    </div>
    <p>Your input: {{ usernameControl.value }}</p>
  `
})
export class SimpleInputComponent {
  usernameControl = new FormControl('', Validators.required);
}
OutputSuccess
Important Notes

Use formControl.value to get the current input value.

Use formControl.invalid and formControl.touched to show validation messages only after user interaction.

You can reset the control with formControl.reset() to clear the value and status.

Summary

FormControl manages one input's value and validation.

It helps track user input and show errors easily.

Use it for simple inputs or inside bigger forms.