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.

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay