DEV Community

Ushmi Dave
Ushmi Dave

Posted on

2

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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay