0

I am using ngModel in the template and when the variable length becomes 16 and if continue typing then it should trim last character but it is not doing so. And when I trim 2 characters then it starts working.

My agenda is to limit text input up to 16 characters but if someone presses comma then it is allowed.

I know we can directly limit the max length using "maxlength" directive on input box, but I have some conditions to satisfy so do not want to use that.

https://stackblitz.com/edit/ngmodel-tag-issue?file=src/app/app.component.ts

Ashish S
  • 638
  • 6
  • 14

1 Answers1

0

Maybe split up the two way binding. Pass the value into the change-fn, process the value and assign it back to the input (via ElementRef) and the model.

onTagInputTextChange(value: string) {
    console.log('onTagInputTextChange', value);
    this.resetCount();
    const tags = value.split(',');
    if (tags.length > 1) {
        tags.forEach((item, i) => {
            if (i < tags.length - 1) this.config.maxTagInputChars += item.length + 1;
        });
    } else {
        if (tags[0].length > 16) {
            value = value.slice(0, 16);
            console.log('value sliced to:', value);
        }
        this.config.maxTagInputChars = 16 * tags.length;
    }

    this.tagInputText = value;
    //  not sure why the [ngModel] binding is not picking up the change on this.tagInputText...
    this.tagInputBox.nativeElement.value = value;
}

<input
    #tagInputBox
    type="text"
    placeholder="Add tag"
    [ngModel]="tagInputText"
    (ngModelChange)="onTagInputTextChange($event)"
/>

https://stackblitz.com/edit/ngmodel-tag-issue-y6f8ud?file=src/app/app.component.ts

1ppCH
  • 276
  • 1
  • 3
  • 13