Skip to content

Instantly share code, notes, and snippets.

@zzpmaster
Last active November 3, 2021 05:13
Show Gist options
  • Save zzpmaster/50c0a8b219e6de23ee0ed0cb3012edb5 to your computer and use it in GitHub Desktop.
Save zzpmaster/50c0a8b219e6de23ee0ed0cb3012edb5 to your computer and use it in GitHub Desktop.
Angular - input formControl limit max length
<!--
使用[inputlimit], 可以使用默认值。
使用[inputlimit]="2", 可以设置要check的长度。
note that: 不能直接使用 inputlimit或inputlimit="2" 会导致默认值为空或是字符串类型。
-->
<input type="text" [inputlimit]="2" formControlName="name" />
import {
Directive,
ElementRef,
Input,
HostListener,
Renderer2,
forwardRef,
} from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[inputlimit]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputLimitDirective),
multi: true,
},
],
})
export class InputLimitDirective extends DefaultValueAccessor {
@Input() inputlimit: number = 3;
constructor(renderer: Renderer2, elementRef: ElementRef) {
super(renderer, elementRef, true);
}
@HostListener('input', ['$event.target.value'])
public input(event: string) {
if (event.length > this.inputlimit) {
const transformed = event.substring(0, this.inputlimit);
super.writeValue(transformed);
this.onChange(transformed);
}
}
public writeValue(value: string) {
window.requestAnimationFrame(() => {
this.input(value);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment