[英]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?我怎样才能做到这一点?
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);
If your class only has properties (not method) use interface .如果您的类只有属性(而不是方法),请使用interface 。 If you use interface you can "cast" simply using:如果您使用界面,您可以简单地使用“投射”:
this.customerservice.processCustomer(this.CustomerGroup.value as CustomerInterface);
Else you need create an object of the class CustomerClass and pass:否则,您需要创建类 CustomerClass 的对象并传递:
const customer=new CustomerClass();
customer.custNo=this.CustomerGroup.value.custNo;
...
this.customerservice.processCustomer(customer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.