Ion-texarea elastic directive


#1

I’ve been working on a project recently which has a form with an ion-textarea inside that contains long text. A problem with ion-textarea for me was that it shows only two lines of text and users have to scroll through the text to change it.

So, I decided to create a directive which would resize the height of ion-textarea base on its contents.
The main requirement for the directive was that it should be a simple attribute directive. In other words, it shouldn’t be a wrapper on ion-textarea, so it’s possible to use the API of ion-textarea.

Here is how it looks - ion-textarea is resized initially to fit its text.

There is also a Plunker demo.

Note: for some reason vertical scrollbar appears on ion-textarea in Plunker, which doesn’t happen when testing in a browser or in a device though.

Usage:
<ion-textarea elasticTextArea [(ngModel)]="description"></ion-textarea>


About to give up with IONIC 3 - Simple Native-like chat page not possible
Why is my directive not working?
#2

Nice!

For the demo to be more impressive, maybe add ad “default” ion-textarea with the same text above oder beneath your elastic one so that the difference is clearly visible.


#3

Hi @Sujan12, good idea!
I updated the plunk.


#4

Shame that http://plnkr.co/ seems to be having problems :confused:


#5

@eakoriakin

really cool idea :slight_smile:

Is it possible that your plunkr url in the first post shows to another example? When I open it it’s about : Ionic 2 Select with Searchbar


#6

Hi @tobika! Oh, sorry, wrong plunk. I think I changed it accidentally :slight_smile:
Here is a correct link.


#7

Nice snip. Thanks for posting this.

I did make one small modification.

Instead of:

            this.textInput._native.valueChange.subscribe((inputValue: any) => {
                this.resize();
            });

I am using:

            this.textInput._native.ngControl.valueChanges.subscribe(() => {
                this.resize();
            });

Why? The problem with TextInput._native.valueChange (for me at least) is that this method is monitoring specifically the value of the textarea it is subscribed to.

If you do any manipulation of the textarea’s ngModel in the backend, TextInput._native.valueChange won’t pick it up. However by pointing the subscriber directly to the ngControl, we can make this elastic directive hook to something that is more static. Since the ngControl value updates whenever the textarea value updates, this likewise still triggers the script as it should.

Cheers


#8

Quick update here, if anyone is using my modification for the ion-textarea elastic directive, you no longer need the _native property. That means that the proper code is:

this.textInput.ngControl.valueChanges.subscribe(() => {
      this.resize();
});

I also had to change (under resize):

this.textInput._elementRef.nativeElement.style.height = height + 'px';

Issue with Prod build?