Woogielicious
Woogielicious

Reputation: 224

How do i format a value in Angular-formly

I have to convert my input value from number to currency only after blur. But i can write it only in console.log, is it not possible to write it back in the view?

Look at the Demo And open the console. write any number and u see what the converter do. I need the Value in my input field.

Upvotes: 2

Views: 5139

Answers (3)

Shoniisra
Shoniisra

Reputation: 781

This worked for me:

 {
    key: 'scorePoints',
    type: 'input',
    templateOptions: {
      label: 'Points',
      placeholder: 'Insert Points',
      type: 'number',
      required: false,
      allowedKeys: '[0-9]',
    }
  }

This allows the user to enter only numbers, although when I receive the value of the model I get it as a string, it is enough to make a casting to number..

However, if you want to recieve a number it is good to initialize the model.

Setting the object field to 0 already forces the field to be returned as numeric.

form = new FormGroup({});
model : MyFormInterfaceModel ={
    levelName:'Level 1',
    scorePoints:0
  };

Upvotes: 0

Known Technical
Known Technical

Reputation: 11

I did this in the below way, We can use blur event under the templateOptions

templateOptions: {
                                    label: 'Minimum Value',
                                    placeholder: 'Minimum Value',
                                    type: 'text',
                                    keydown: (field, $event) => {
                                        return ValidateNumericChars(field, $event);
                                    },
                                    focus: (a, event) => {
                                        event.target.value = Number(event.target.value.replace(/[^0-9.-]+/g, ""));
                                    },
                                    blur: (a, event) => {
                                        event.target.value = this.utility.formatCurrency(event.target.value);
                                    }
                                },

Upvotes: 0

a.aitboudad
a.aitboudad

Reputation: 4092

The solution is to create a custom field type that uses one of the following option:

  1. ngx-currency https://stackblitz.com/edit/ngx-formly-custom-template-ol5cs9
  2. ngx-mask
  3. custom directive which relies on on ControlValueAccessor: https://stackblitz.com/edit/angular-hv7mnc

Upvotes: 4

Related Questions