Reputation: 101
Is there a way to limit the amount of letters that can be put into an inputfield depending on the size it takes up?
For example W's and M's take enough space to place 34 of them.
But if i use normal sentences the same amount of letters is only taking half of the size up in comparison to the W's and M's.
What i want is that i can basically write anything as long the Size of the inputfield is big enough. Is that possible?
Upvotes: 3
Views: 60
Reputation: 140
First, you can access to the size of your input with something like this :
const ele = document.getElementById('yourInputId');
const eleStyle = window.getComputedStyle(ele);
const inputSize = {width: eleStyle.width, height: eleStyle.heigth};
Then, in another method, assuming you know the font and font-size of your text (if you don't, check Angular Documentation), you can set-up a method like this :
pixelLength(txt: string, font: number) {
const canva = document.createElement('CANVAS');
const attr = document.createAttribute('id');
attr.value = 'myId';
canva.setAttributeNode(attr);
document.body.appendChild(canva);
const c: any = document.getElementById('myId');
const ctx = c.getContext('2d');
ctx.font = font.toString() + 'px Helvetica';
const result = ctx.measureText(txt).width;
document.body.removeChild(canva);
return result;
}
You might want to call this method in a custom form control, to check if it will be longer than inputSize.width
.
Let me know if something's unclear ;)
Happy coding.
Upvotes: 1