Reputation: 1814
I'm using Reactive Forms
and I want to convert the value of formGroup
into Model class object. Please give me some solutions for it. and also I want to send only password
fields not confirmPasword
. I also mentioned my model class .
Service.ts
objRegisterModel: RegisterModel = new RegisterModel();
constructor(private fb: FormBuilder, private http: HttpClient) {}
formModel = this.fb.group({
FirstName: ['', Validators.required],
LastName: ['', Validators.required],
Emails: this.fb.group({
EmailID: ['', [Validators.required, Validators.email]],
ConfirmEmail: ['', Validators.required]
}, { validator: this.compareEmails }),
OrgName: ['', Validators.required],
OrganizationType: ['', Validators.required],
City: ['', Validators.required],
PhoneNo: ['', Validators.required],
PostalAddress: ['', Validators.required],
Passwords: this.fb.group({
Pwd: ['', Validators.required],
ConfirmPassword: ['', [Validators.required]]
}, { validator: this.comparePasswords })
});
Model Class
export class RegisterModel {
Active: number;
Address: string;
Amt: number;
CityID: number;
Country: string;
EmailID: string;
FullName: string;
ID: number;
PhoneNo: string;
PostalAddress: string;
Pwd: string;
constructor(init?: Partial<RegisterModel>) {
Object.assign(this,init);
}
}
Upvotes: 1
Views: 5477
Reputation: 84
As simple as this:
objRegisterModel: RegisterModel = this.formModel.value
vote up the answers that helped you the most! If these answers were helpful to you
Upvotes: 4
Reputation: 242
Well, your model class don't have all the fields as in form. I consider it as your mistake, you should add all fields in the model then make and use some mapping function like
mapping(group: FormGroup){
Object.keys(group.control).forEach(key =>{
const abstractControl = group.get(key);
if(abstractControl && abstractControl instanceof FormGroup){
//call recursively
mapping(abstractControl);
}
else{
if(key !== 'ConfirmPassword')
this.objRegisterModel[key] = abstractControl.value;
}
}//end of forEach
}//end of func
Now you just need to call this function passing object of FormGroup. Hope it helps you
Upvotes: 0
Reputation: 42516
First and foremost, instead of using a Class for defining RegisterModel
, I would recommend you to use an Interface instead.
export interface RegisterModel {
Active: number;
Address: string;
Amt: number;
CityID: number;
Country: string;
EmailID: string;
FullName: string;
ID: number;
PhoneNo: string;
PostalAddress: string;
Pwd: string;
}
On your component/service that requires the above interface, we first initialise the objRegisterModel
property.
objRegisterModel: RegisterModel = {} as RegisterModel;
To get the values of your Reactive Form FormGroup
, you can simply do this:
this.formModel.value
If you want to get only the password, and I assuming you are referring to the Pwd
property,
this.formModel.Passwords.Pwd
Upvotes: 0