Angular 5 directive for dynamic text input width

Andreas Pogiatzis
1 min readAug 2, 2018

--

I am not sure if this classify as a blog post but rather as a code snippet. Still, I wanted to publish it here in case someone of you come across a similar scenario that needs a reusable dynamically updated HTML element based on its content.

This is a pretty simple code snippet to define an Angular directive which can be used to enable dynamic width on text inputs.

I found that many people use anti-Angularish ways to achieve the same thing so I thought that it worths posting the correct Angular-way to do it.

Angular directive for dynamic width

More particularly I used that in an inline edit text component. It came handy since when the user edits the text in place, the text box resizes automatically without messing up my layout.

To use it just add the directive selector on the input element like this:

<input type="text" appAutowidth/>

Oh! And don’t forget to add it to your app declarations otherwise it won’t work!

In the same manner, directives can be defined to adjust other more complex properties of the element. You can think of directives as decorators. Use them to adjust element’s behavior that is outside of the scope of the component implementation.

Enjoy!

--

--

Andreas Pogiatzis
Andreas Pogiatzis

Written by Andreas Pogiatzis

☰ PhD Candidate @ UoG ● Combining Cyber Security with Data Science ● Writing to Understand

Responses (4)