DEV Community

Cover image for Angular 2+ dynamic input width 📏
Răzvan Stătescu
Răzvan Stătescu

Posted on

1

Angular 2+ dynamic input width 📏

I've recently had a project where I had to dynamically adjust the width of an input, based on the content size.

It might sound hard to do, but in reality is very simple. We achieve this by taking advantage of the size attribute.

We start by creating a new Angular directive using ng g directive [path]

After that, we write our directive as follows:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[dynamic-input]',
})
export class DynamicInputDirective {
constructor(private el: ElementRef) {
this.resize();
}
@HostListener('keyup') onKeyUp() {
this.resize();
}
private resize() {
this.el.nativeElement.setAttribute(
'size',
this.el.nativeElement.value.length || 2
);
}
}

Now, you can use it like this: <input type="text" dynamic-input />

Top comments (1)

Collapse
 
kottartillsalu profile image
Maxime

This doesn't work if the input has an initial value.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay