6
在名称字段中有一些限制,所以我试图使用下面的指令验证名称字段。内部指令我正在使用正则表达式来检查有效的名称,然后使用valueAccessor.writeValue(newVal)
Angular 2光标在文本框末尾跳转时更改数据
将有效的名称替换为文本框这里的问题是当我试图键入文本框中的某个单词时光标跳到最后。
@Directive({
selector: '[validateName]',
host: {
'(ngModelChange)': 'onInputChange($event, false)',
'(keydown.backspace)': 'onInputChange($event.target.value, true)',
'(focusout)': 'removeClass()'
}
})
export class NameValidator {
constructor(public model: NgControl,public renderer: Renderer, public el: ElementRef) { }
onInputChange(event, backspace) {
if (!backspace) {
// Remove invalid characters (keep only valid characters)
var newVal = event.replace(/^[0-9\s]/g, '').replace(/[^A-Za-z0-9_$]/g,'');
// Add class for invalid name.
if (/^[0-9\s]/g.test(event) || /[^A-Za-z0-9_$]/g.test(event)) {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', true);
}
else {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
}
}
removeClass() {
this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false);
}
}
'this.el.nativeElement.s etSelectionRange(开始,结束);'为我工作。这是非常酷的人。 –