DEV Community

Ushmi Dave
Ushmi Dave

Posted on

Make angular reactive forms strongly typed.

Reactive forms are complex, Hence they must be strongly typed with the respective model.

This can be achieved through IFormGroup

Let's see how:

1) Install @rxweb/reactive-form-validators

npm i @rxweb/reactive-form-validators

2) Create user model class and declare property of fullName.

import { prop } from "@rxweb/reactive-form-validators"

export class User{

  @prop()
  fullName:string;

}
Enter fullscreen mode Exit fullscreen mode

3) Now create the Component which uses IFormGroup<User> to make your form stronglyTyped with model.

import { Component, OnInit } from '@angular/core';

import { RxFormBuilder,IFormGroup } from '@rxweb/reactive-form-validators';
import { User } from "./user.model"

@Component({
    selector: 'app-user',
    templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {

    userFormGroup: IFormGroup<User>

    constructor(
        private formBuilder: RxFormBuilder
    ) { }

    ngOnInit() {
        this.userFormGroup  = this.formBuilder.formGroup(User) as IFormGroup<User>;
        this.userFormGroup.controls.fullName.setValue("John");
        let fullName = this.userFormGroup.value.fullName;

    }

}
Enter fullscreen mode Exit fullscreen mode

4) Create user form in the HTML:

<div>
    <form [formGroup]="userFormGroup">
        <div class="form-group">
            <label>Full Name</label>
            <input type="text" formControlName="fullName" class="form-control" />
        </div>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode

Please refer this working example

Top comments (0)