DEV Community

Ushmi Dave
Ushmi Dave

Posted on

Class Abstraction in angular reactive forms

While using model driven approach in angular reactive forms, we might be in need to use the properties of base class into derived class.

Here is a way to access properties of base class into derived class and also hide the complexity of inherited classes.

Step 1:
Install @rxweb/reactive-form-validators

npm i @rxweb/reactive-form-validators

Step 2:
Suppose you are having two classes Product and Order, You want to use properties of Product into Order

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

export class Product{

  @prop()
  productId:number;

  @prop()
  productName:string;
}

export class Order extends Product  {
   @prop()
   orderId:number;

   @prop()
   orderType:string;
}
Enter fullscreen mode Exit fullscreen mode

Step 3:
Create Component using formGroup method of RxFormBuilder to use the model Object

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

import { RxFormBuilder } from '@rxweb/reactive-form-validators';

import { Order } from './order.model';

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

    userFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder
    ) { }

    ngOnInit() {
        let order = new Order();
        this.userFormGroup = this.formBuilder.formGroup(order);
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 4:
Create form in component HTML

<form *ngIf="userFormGroup" [formGroup]="userFormGroup">
    <div class="form-group">
        <label>Product Id</label>
        <input type="text" formControlName="productId" class="form-control" />
    </div>
    <div class="form-group">
        <label>Product Name</label>
        <input type="text" formControlName="productName" class="form-control" />
    </div>
        <div class="form-group">
        <label>OrderId</label>
        <input type="text" formControlName="orderId" class="form-control" />
    </div>
     <div class="form-group">
        <label>Order Type</label>
        <input type="text" formControlName="orderType" class="form-control" />
    </div>
    <button [disabled]="!userFormGroup.valid" class="btn btn-primary">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Here is the working example

In Case of query/suggestion, Please comment below

Top comments (0)