Issue
I can't share actual images or code due to NDA, so I'll explain through examples.
I have an Angular reactive form that contains the following input fields:
- Name
- Description
- Data type (this is a select input with the following options)
- STRING
- NUMBER
- DATE
- Input field that's shown based on the selected data type
Based on the data type the user selects, a different input field is shown on the UI using *ngIf
. For instance, on selecting type 'STRING', a field that takes in the max-length of the string is displayed; on selecting 'DATE', a select input with date formats as different options is displayed.
I am building a form in ngOnInit()
with all these properties initially set to empty string, like shown below in the image link
While sending the form data to the backend, I'm sending this.formData.values
. If the user has selected 'NUMBER' data type, scale
& precision
will have the values from the inputs and maxLength
& format
will be empty strings, and similarly, the other fields will be empty strings for other data types.
Now my question, is there an easy and simpler way to send only the form values of the properties being used and exclude the form properties with empty strings?
P.S I don't know if my question is phrased properly, please omit the mistakes
Solution
Here is a solution using removeControl
to exclude the fields with empty strings
remove() {
Object.keys(this.demoForm.controls).forEach((key) => {
if (this.demoForm.controls[key].value == '') {
this.demoForm.removeControl(key);
}
});
}
See this demo
Answered By - Merna Mustafa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.