How to create an auto-grow directive in Angular 2

How to create an auto-grow directive in Angular 2

This article will explain how you can create a directive to automatically adjust the height of a textarea to its content.

Step 1 – create the directive with angular-cli

If you have not already, install angular-cli.
Go to the root of your project (the folder containing “package.json”), open a shell and execute the following statements:

These statements will create a basic directive file and wire it into your application.

You can change the selector to ‘[autoGrow]’ if you want.

Step 2 – add the auto-grow code

Change the code of the auto-grow directive as follows:

Save this file and it is ready for use.

Step 3 – using the directive

We are ready to use the directive.

We do not need to add the directive to the Angular module anymore because the angular-cli already did this for us. If you want to copy-paste the above code in a manually created file, you will need to open up your app.module.ts file and add the directive to the declarations yourself. See “Adding the directive to your module manually”.

To use the directive, simply add the selector to a textarea as follows. Note that we use the “dash-case” notation in HTML!

That is all it takes!


This article showed you how you can implement an auto-grow directive in 3 easy steps.