1

I have data coming from server that are formatted in meters but in the interface I need to display and edit in inches then send it back to server again in meters. There is some technique to handle the conversion dynamically, say using a converter function bound to formControl or whatever? I'm using angular material components.

Thanks in advance

5
  • The short answer is yes there are a lot of "techniques" to handle that conversion dynamically. We'd be way more useful if you show us how you're trying to do that so we can guide you. Commented Feb 28, 2020 at 14:42
  • Hi! You could use ngModel which creates a FormControl instance from a domain model and binds it to a form control element. stackblitz.com/edit/angular-vwrn2j?file=src/app/… Commented Feb 28, 2020 at 14:42
  • I don't have an example tho show, but in short I use patchValue() to apply data than the value property to get data to send back to server Commented Feb 28, 2020 at 14:54
  • @salgaf Can you not create an example in stackblitz? Commented Feb 28, 2020 at 15:01
  • For me, who must mannage the conversion is the service. Use pipe(map(x=>...)) after the httClient.get the value/s and before send the data make the proper conversion. This allow your component works on inches Commented Feb 28, 2020 at 15:49

2 Answers 2

1

One of the best way is to actually make use of a directive to do your conversion to inches so that you don't have to worry about the server data.

something like this:

<form [formGroup]="newForm" (ngSubmit)="onSubmit()">
 <input formatData formControlName="data"/>
</form>

onSubmit() {
// ...conversion back to meters
}

I am using reactive forms as that is more dynamic and something that I use a lot as I build my forms dynamically but you can also do the same with template forms.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm also using reactive forms , have you an example to follow?
0

You could use Angular Pipes to transform the data and then display them in your Interface (view).

Pipes are angular decorated class that implements a transform function which takes in data as input and transforms it to a desired output and show them to users (as they can be added to your HTML). You can read more about them here, and write a Custom Pipe for your purpose.

2 Comments

Pipes is usable in two ways? I mean convert for the interface and convert back for the data to send?
No they will only convert data to display for interface, to convert the data back create a reverse function and call it while submitting the form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.