I am working on Angular 6 on a pretty simple example.
I am creating a Directive that I can put on my textareas so that they resize themselves automatically.
However, I have an issue using host binding. I want to check if resize is needed before resizing, but I cannot check: this.height gives undefined by default.
Even worse, if it has been resized manually, this.height remains undefined anyway.
I've tried using the @Input decorator on top of the @HostBinding, but this just sets an initial value, and then when resizing, height doesn't match the real size of the element anymore.
I can't seem to find out why it doesn't work, could you please help ?
Also I am conscious that an alternative to what I'm trying to do would be to just set the height of my directive to the native element scrollheight without checking prior, but then I wouldn't understand why my height value is undefined/doesn't dynamically update.
Here is my code:
simple.component.html
<textarea type="text"
class="form-control mb-1"
appAutoResizeTextArea></textarea>
simple.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-simple-component',
templateUrl: './simple.component.html',
styleUrls: ['./simple.component.css']
})
export class SimpleComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
auto-resize-text-area.directive.ts
import { Directive, ElementRef, HostListener, Renderer2, HostBinding, Input } from '@angular/core';
@Directive({
selector: '[appAutoResizeTextArea]',
})
export class AutoResizeTextAreaDirective {
@HostBinding('style.height.px') height;
@HostListener('input')
onKeyDown(){
console.log(this.height); // gives 'undefined'
if(this.height < this.el.nativeElement.scrollHeight || this.height > this.el.nativeElement.scrollHeight)
this.height = this.el.nativeElement.scrollHeight;
}
constructor(private el:ElementRef, private renderer:Renderer2) { }
}
Thanks for your help