import { Directive, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[characterCount]'
})
export class CharacterCounterDirective {
constructor(private el: ElementRef) {}
@Input('characterCount') maxLength: number;
ngOnInit() {
let counter = document.createElement("div");
counter.innerHTML = "0/" + this.maxLength;
this.el.nativeElement.parentElement.appendChild(counter);
this.el.nativeElement.addEventListener("input", () => {
let currentLength = this.el.nativeElement.value.length;
if (currentLength > this.maxLength) {
this.el.nativeElement.value = this.el.nativeElement.value.slice(0, this.maxLength);
currentLength = this.maxLength;
}
counter.innerHTML = currentLength + "/" + this.maxLength;
});
}
}
这将在文本区域下方显示一个计数器,它将显示已输入的字符数和文本框允许的最大字符数。当输入超过设定的最大字符数时,它将限制输入并显示字符计数。