'Angular (Material UI) - format ssn on user input
I have the following problem. I have ssn input which has to be formatted like xxx-xx-xxxx and I can achieve this using pipe transformation
<mat-label>SSN</mat-label>
<input matInput type="text" [ngModel]="ssn | ssn" (ngModelChange)="transformSsn($event)">
</mat-form-field>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'ssn'
})
export class SsnPipe implements PipeTransform {
transform(a: string, ...args: unknown[]): unknown {
var fSSN = '';
fSSN += a.substr(0, 3);
fSSN += '-' + a.substr(3, 2);
fSSN += '-' + a.substr(5, 4);
return fSSN;
}
}```
But somehow I have to distinguish viewValue, which has to be xxx-xx-xxxx with modelValue which has to be xxxxxxxx( simple number). I've tried to add transformSsn function call on modelChanges event, but still no luck. Any help would be highly appreciated.
Solution 1:[1]
What if you expand the transform() to check if string a already contains some -'s? And if so return and do nothing? You could of course expand this if check the check if the -'s are in exact index that you want, but the point is same.
transform(a: string, ...args: unknown[]): unknown {
if (a.includes('-') return;
var fSSN = '';
fSSN += a.substr(0, 3);
fSSN += '-' + a.substr(3, 2);
fSSN += '-' + a.substr(5, 4);
return fSSN;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joosep Parts |
