有可能在角度2中有模型驱动形式,并找到可以屏蔽输入字段(如电话号码输入)的指令
(123)123-4567?
(123)123-4567?
Plunker >= RC.5
原文链接:https://www.f2er.com/angularjs/143025.html原版的
您可以使用一种方法来使用注入NgControl并操纵该值的指令
(详情请参阅内线评论)
@Directive({ selector: '[ngModel][phone]',host: { '(ngModelChange)': 'onInputChange($event)','(keydown.backspace)': 'onInputChange($event.target.value,true)' } }) export class PhoneMask { constructor(public model: NgControl) {} onInputChange(event,backspace) { // remove all mask characters (keep only numeric) var newVal = event.replace(/\D/g,''); // special handling of backspace necessary otherwise // deleting of non-numeric characters is not recognized // this laves room for improvement for example if you delete in the // middle of the string if (backspace) { newVal = newVal.substring(0,newVal.length - 1); } // don't show braces for empty value if (newVal.length == 0) { newVal = ''; } // don't show braces for empty groups at the end 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,'($1) ($2)'); } else { newVal = newVal.replace(/^(\d{0,3})(.*)/,'($1) ($2)-$3'); } // set the new value this.model.valueAccessor.writeValue(newVal); } }
@Component({ selector: 'my-app',providers: [],template: ` <form [ngFormModel]="form"> <input type="text" phone [(ngModel)]="data" ngControl="phone"> </form> `,directives: [PhoneMask] }) export class App { constructor(fb: FormBuilder) { this.form = fb.group({ phone: [''] }) } }