Masked data integration in angular

39 Views Asked by At

I'm having trouble with something. I want to add a mask to one of my inputs to change how it looks on the screen, but I still need to send the original data to the backend. The mask component seems to work when I create and view it, but when I try to edit it, it doesn't update the data correctly. It doesn't remove what I delete, and it just adds new symbols when I type. Also, when I click on edit initially, it shows the input without the mask until I clear it.

when trying to create - it should be like this:

input -> 12345678 - in UI it should be visible 1234****

sending to the backend exact data -> 12345678

when trying to edit - it should be like this:

it has to be visible in input 1234****
                  
when click save to update it, it should set the exact data which I added

for both cases, the same component has been called

I have created mask input component:

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'mask,
  templateUrl: './mask.component.html',
})
export class InputMaskComponent implements OnInit{
  @Input() name: string;
  @Input() control: FormControl;
  @Input() e2eName: string;
  @Output() valueChange = new EventEmitter<string>();
  actualValue = '';
  maskedValue = '';

  ngOnInit() {
   this.actualValue = this.control.value;
  }
  emitActualValue(value: string): void {
    this.actualValue = value;
    this.valueChange.emit(this.actualValue);
  }

  maskInput(event: Event): void {
    const inputEvent = event as InputEvent;
    const inputElement = event.target as HTMLInputElement;
    const inputData = inputEvent.data;
    const inputValue = inputElement.value;
    if (inputData != null) {
      this.actualValue += inputData;
    }
    this.emitActualValue(this.actualValue);
    this.maskedValue = inputValue.substring(0, 4) + '*'.repeat(Math.max(0, inputValue.length - 4));
    inputElement.value = this.maskedValue;
  }
}

<label>
    <span>{{ name }}</span>
  <div class="control">
    <input
      [formControl]="control"
      [attr.data-e2e]="e2eName"
      type="text"
      class="input"
      (input)="maskInput($event)"
    />
  </div>
</label>

and use it here:

<mask
  name=“masked label“
  [control]=“maskedControl”
  [e2eName]="'input-mask’”
  (valueChange)="handleValueChange($event)"
  data-e2e="maskedControl"
  i18n-name
></mask

handleValueChange(value: string): void {
  this.maskedControl.setValue(value);
}

get maskedControl(): AbstractControl {
  return //to get masked control value, from the API
}

Currently this code doesn't work:

  1. when I try to edit my data, it shows old and deleted value too
  2. in the beginning * doesn't visible until I click on that input
0

There are 0 best solutions below