Skip to content
Advertisement

Convert Form Group data to a class in Angular/Typescript

I have a form group that is being passed into the component as input parameter and I need to pass that to a method as an object of the class. Is there a easy way to convert the form group which contains the form control into a class

Class

export class CustomerClass{
  custNo?: string;
  CustName?: string;
  CustAddress: string;
}

FormGroup

    const group: FormGroup = this._fb.group({
      CustAddress: this._fb.control('test'),
      custNo: this._fb.control(''),
      CustAddress: this._fb.control(''),
    });

Component

  @Input()
  CustomerGroup: FormGroup;

//Now I need this as a object of class to pass it to a function

submit() {
this.customerservice.processCustomer(CustomerGroup);

}

Service

processCustomer(customer: CustomerClass){
//do stuff
}

Can I easily convert the form group to a class? How can I do that?

Advertisement

Answer

Did you try by getting the value from the form ? It will returns an object with the class properties.

    this.customerservice.processCustomer(this.myForm.value);

//in your case if you want to send the form object that you are getting in the input.

    this.customerservice.processCustomer(this.CustomerGroup?.value);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement