我已经使用Angular2指令屏蔽了电话号码和SSN。但我需要用星号()替换屏蔽的SSN。 例如:输入SSN:123-45-6789,输出SSN: - - ****。 我拥有:输入SSN:123456789,输出SSN:123-45-6789。 工作的Plunker代码:https://plnkr.co/edit/XrqvSuge65Oi7IovBa8Y?p=preview
masking.component.ts
import {Component, Directive, Output, EventEmitter} from '@angular/core';
import {FormBuilder, FORM_DIRECTIVES, NgControl} from '@angular/common';
import {PhoneMask} from './phoneMask.directive';
import {SsnMask} from './ssnMask.directive';
@Component({
selector: 'masking',
providers: [],
template: `
<form [ngFormModel]="form">
Phone:<input type="text" phone [(ngModel)]="data" (rawChange)="rawPhone=$event" ngControl="phone" maxlength="14">
SSN:<input type="text" ssn [(ngModel)]="ssndata" (rawChange)="rawSsn=$event" ngControl="ssn" maxlength="11">
</form>
<div>Raw Numbers: {{rawPhone}}</div>
<div>SSN: {{rawSsn}}</div>
`,
directives: [PhoneMask,SsnMask]
})
export class Masking {
form :any;
constructor(private fb:FormBuilder) {
this.form=fb.group({
phone:[''],
ssn:['']
})
}
}
ssnMask.directive.ts
import {Directive,Output,EventEmitter} from '@angular/core';
import {NgControl} from '@angular/common';
@Directive({
selector:'[ngModel][ssn]',
host:{
'(ngModelChange)':'onInputChange($event)',
'(keydown.backspace)':'onInputChange($event.target.value,true)'
}
})
export class SsnMask{
constructor(public model: NgControl){}
@Output() rawChange:EventEmitter<string> = new EventEmitter<string>();
onInputChange(event,backspace){
var newVal=event.replace(/\D/g,'');
var rawValue= newVal;
if(backspace){
newVal=newVal.substring(0, newVal.length);
}
if(newVal.length==0){
newVal='';
}
else if(newVal.length<=3){
newVal=newVal.replace(/^(\d{0,3})/, '$1');
}
else if(newVal.length <=6){
newVal=newVal.replace(/^(\d{0,3})(\d{0,2})/, '$1-$2');
}
else if(newVal.length<=9){
newVal=newVal.replace(/^(\d{0,3})(\d{0,2})(\d{0,4})/, '$1-$2-$3')
}
this.model.valueAccessor.writeValue(newVal);
this.rawChange.emit(rawValue);
}
}