Issue
I have a requirement where I have an input field. In that input field I am passing string value seperated by commas. I am storing each input value in array. I want to restrict user from entering more than 4 characters.
For example: Suppose we have this input
["mango","papaya","jackfruit"]
I want like
["mang","papa","jack"]
I want that when someone enters more than 4 character it wont allow user to enter anything thereafter. If he presses comma then he is allow to write another string value of 4 character
component.html
<input formControlName="name" (keypress)="singleElement($event)" (input)="inputName($event)">
component.ts
inputName(event){
this.value = (<HTMLInputElement>event.target).value
}
singleElement(event) {
return(
(event.charCode > 64 && event.charCode < 91) ||
(event.charCode > 96 && event.charCode < 123) ||
(event.charCode > 47 && event.charCode < 58) ||
event.charCode == 44
)}
Solution
Try this:
form = new FormGroup({
name: new FormControl(''),
});
previousValue = '';
@ViewChild('myTags') tags!: ElementRef;
inputName(event: any) {
const value = event.target.value;
const tags = value.split(',');
if (tags.some((t: any) => t.length > 4)) {
const caretPosition = this.tags.nativeElement.selectionStart;
this.form.patchValue({ name: this.previousValue });
this.tags.nativeElement.selectionStart =
this.tags.nativeElement.selectionEnd = caretPosition - 1;
return;
}
this.previousValue = value;
}
When the input field is updated it checks if any of the max-four character tags is longer than 4. If so, it replaces the form field with the previous value and sets caret to the previous position (otherwise it would jump to the end of the string).
Check this working example: https://stackblitz.com/edit/stackblitz-starters-quyczz?file=src%2Fmain.ts
Answered By - Kari F.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.