效果如下图:显示当前输入长度 / 最大限制

这个例子是限制长度,如果需要限制输入的字符类型(如只能输入数字、英文。。。)可以在这onkeypress / onInput两个方法作相应处理。
直接上代码
import { Directive, ElementRef } from '@angular/core';
import { NgControl, NgModel } from '@angular/forms';
@Directive({
selector: 'input[inputLen]',
// providers:[NgModel] // 如果报 no providers for NgModel, 加这一行
host: {
'(keypress)': 'onkeypress($event)',
'(input)': 'onInput($event)',
},
inputs: ['inputLen'],
})
export class InputLenDirective {
maxLength: number;
inputLen: number;
constructor(
private el: ElementRef,
public ngControl: NgControl,
public ngModel: NgModel
) {}
ngOnInit() {
this.maxLength = this.inputLen;
}
ngAfterViewInit() {
this.handle();
}
onkeypress(event) {
if (event.target.value.length >= this.maxLength) {
return false;
}
}
onInput(event) {
let input = event.target;
if ((input.value.length) >= this.maxLength) {
const cutValue = input.value.substr(0,this.inputLen);
this.ngControl.control.patchValue(cutValue); // 如果用表单, 需要patchValue更新表单的值
// this.ngModel.viewToModelUpdate(cutValue); // 如果用ngModel,可以直接用viewToModelUpdate
}
this.handle();
}
/**
* 显示当前长度与限制长度 4/12
* 按自己需要,appendTo到适合的元素上
*/
private handle() {
const $wrap = $(this.el.nativeElement).closest('.ant-form-item-control');
let $tips = $wrap.find('.input-len-postfix');
if (!$tips.length) {
$tips = $(`<div class="input-len-postfix">${this.buildPostfix()}</div>`);
$tips.css({
position: 'absolute',
right: '10px',
'font-size': '12px',
color: '#999',
transform: 'translateY(-50%) scale(0.83)',
top: '50%',
'transform-origin': 'center right',
});
$tips.appendTo($wrap);
} else {
$tips.text(this.buildPostfix());
}
}
private calcLen() {
let value = $(this.el.nativeElement).val();;
return value.length;
}
/**
* 拼接显示:当前长度 / 限制长度, 如4/12
*/
private buildPostfix(): string {
let value = $(this.el.nativeElement).val();;
return `${Math.min(value.length, this.inputLen)} / ${this.inputLen}`;
}
}
2种情况下的使用方法:
<!--
// 通过表单的形式使用
// 指令对应使用:this.ngControl.control.patchValue(cutValue);
-->
<form nz-form [formGroup]="formGroup">
<div><input formControlName="name" inputLen="12"></div>
</form>
<!--
// 通过ngModel绑定的形式使用
// 指令对应使用:this.ngModel.viewToModelUpdate(cutValue); // 如果用ngModel,可以直接用viewToModelUpdate
-->
<div>
<input [(ngModel)]="name" inputLen="12">
</div>
注:demo 代码作了相应的删减,如果报错,可作小调整。

本文介绍了如何在Angular NG2中创建一个自定义指令,用于限制input输入的长度和允许的字符类型。示例展示了如何显示当前输入长度与最大限制,并提供了两种使用情况的代码示例。若要实现特定字符限制,可以在事件处理方法onkeypress或onInput中进行处理。
7446

被折叠的 条评论
为什么被折叠?



