我正在使用Reactive Forms
,并且想将formGroup
的值转换为Model类对象。请给我一些解决方案。而且我只想发送password
字段,而不发送confirmPasword
。我还提到了我的模型课。
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 })
});
模型类
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);
}
}
答案 0 :(得分:1)
就这么简单
objRegisterModel: RegisterModel = this.formModel.value
投票对您有最大帮助的答案!如果这些答案对您有帮助
答案 1 :(得分:0)
首先,我建议您不要使用Class来定义RegisterModel
,而是建议您使用Interface。
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;
}
在需要上述接口的组件/服务上,我们首先初始化objRegisterModel
属性。
objRegisterModel: RegisterModel = {} as RegisterModel;
要获取您的反应式表单FormGroup
的值,只需执行以下操作:
this.formModel.value
如果您只想获取密码,并且我假设您所指的是Pwd
属性,
this.formModel.Passwords.Pwd
答案 2 :(得分:0)
好吧,您的模型类没有像表格中那样包含所有字段。 我认为这是您的错误,您应该在模型中添加所有字段,然后制作并使用一些映射功能,例如
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
现在,您只需要调用此函数传递FormGroup的对象即可。 希望对您有帮助