Home > Software engineering >  Can I set a max and min value to a Mask on Angular?
Can I set a max and min value to a Mask on Angular?

Time:03-30

Well I have two input fields, one for latitude and the other for longitude, that i wat to put a mask on, so the user can only put reasonables values and i wanted to set a max and min values to it and also add the º on the end. But i do not want to set a number of digits the user can type, so im kinda lost in what to do. Can someone help me with this?

These are the two input fields I made:

<input placeholder="{{ module.longitude }}" id="i-long" 
[(ngModel)]="module.longitude" required name="long">
<input placeholder="{{ module.latitude }}" id="i-lat" 
[(ngModel)]="module.latitude" required name="lat"><br>

CodePudding user response:

You can achieve that by creating Angular Directive and use HostListener to watch for a changes in the input field.

By using HostListener you can control the max and min values for the input field and also add the º sign in the end as the example bellow:

 @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value);
  }

  onInputChange(event) {
    let newVal = event.replace(/\D/g, '');
    console.log(newVal);
    if (newVal > 0) {
      newVal = newVal   'º';
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }

After creating the directive you should bind it to the input field.

 <form [formGroup]="form">
      <div >
        <label for="longitude">Longitude</label>

        <input
          
          type="text"
          appLongitudeMask
          formControlName="longitude"
          id="longitude"
        />
      </div>
</form>

Please see stackblitz example of it: https://stackblitz.com/edit/angular6-mask-ftsvf6 I hope this helps you.

CodePudding user response:

use maxlength and minlength

like this :

<input placeholder="{{ module.longitude }}" id="i-long" 
[(ngModel)]="module.longitude" required name="long" maxlength = "10" minlength = "1">

you can use for º on the end many way like use image or icon.

  • Related