We use cookies to enhance your experience on the site
CodeWorlds

Typed Forms (Angular 14+)

Typed Forms provide full type safety - like the precise strokes of a calligraphy master!

Defining Types

1import { FormControl, FormGroup, NonNullableFormBuilder } from '@angular/forms';
2
3// Form interface
4interface SamuraiForm {
5  name: FormControl<string>;
6  level: FormControl<number>;
7  clan: FormControl<string>;
8  skills: FormControl<string[]>;
9}
10
11@Component({...})
12export class TypedFormComponent {
13  // NonNullableFormBuilder - controls cannot be null
14  private fb = inject(NonNullableFormBuilder);
15
16  samuraiForm: FormGroup<SamuraiForm> = this.fb.group({
17    name: ['', Validators.required],
18    level: [1, Validators.min(1)],
19    clan: ['Ronin'],
20    skills: [['Kendo']]
21  });
22
23  onSubmit(): void {
24    // value is fully typed!
25    const formValue = this.samuraiForm.getRawValue();
26    // Type: { name: string, level: number, clan: string, skills: string[] }
27
28    console.log(formValue.name);  // string, not string | null
29  }
30}

FormControl vs FormGroup vs FormArray

1import { FormControl, FormGroup, FormArray } from '@angular/forms';
2
3// FormControl - single value
4const nameControl = new FormControl<string>('');
5
6// FormGroup - object with fields
7const samuraiGroup = new FormGroup({
8  name: new FormControl(''),
9  level: new FormControl(1)
10});
11
12// FormArray - array of controls
13const skillsArray = new FormArray([
14  new FormControl('Kendo'),
15  new FormControl('Iaido')
16]);
17
18// Accessing values
19console.log(nameControl.value);       // string
20console.log(samuraiGroup.value);      // { name: string, level: number }
21console.log(skillsArray.value);       // string[]
Go to CodeWorlds