5

I have 3 text boxes in HTML, each has an initial width of 30px each. I want to make it so that, in the event that someone types into one of the text boxes text such that it exceeds the width of the box, the width of all three text boxes expands to match the size of the largest text box. What is the best way to do this?

Rolando
  • 58,640
  • 98
  • 266
  • 407

1 Answers1

4
@Component({
  selector: 'my-app',
  styles: [`#size
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: nowrap; /* Thanks to Herb Caudill comment */
}`]
  template: `
  <div id="size" #size>{{text}}</div>
  <input #inp [(ngModel)]="text" 
              (ngModelChange)="width=size.clientWidth" 
              [style.width.px]="width > 50 ? width +10 : 60">
  `,
})

Plunker link

It uses a hidden <div> that needs the same font style as the input element and on each change the input will be updated to match the size of the hidden <div> that contains the same text.

See also Calculate text width with JavaScript

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567