html textArea resize event with Angular

2019-09-20 23:59发布

问题:

I have a row-like layout, and on the rows, there are several text areas in embedded divs, just like the following:

 <div class="row-192">
  <div class="inner">
     <p>
       text
     </p>
     <textarea rows="4" cols="40"></textarea>
   </div>
 </div>

If the user resizes the textArea with the small triangle button, I need to adjust the current row height (and other properties) accordingly. I found some solutions in jQuery, but I need to stick to Angular directives only.

demo: http://jsfiddle.net/o0yvysL5/1/

Preferably, I would require some kind of an event, that I can subscribe to, like <textarea (resize)="resizeEvent($event)" ... but there are none.

Any ideas?

回答1:

resizable.textarea.directive.ts

@Directive({
  selector: 'textarea[resize]'
})
export class ResizableTextAreaDirective {
  @Output() resize = new EventEmitter();

  width: number;
  height: number;

  mouseMoveListener: Function;

  @HostListener('mousedown', ['$event.target'])
  onMouseDown(el) {
    this.width = el.offsetWidth;
    this.height = el.offsetHeight;
    this.mouseMoveListener = this.renderer.listen('document', 'mousemove', () => {
      if (this.width !== el.offsetWidth || this.height !== el.offsetHeight) {
        this.resize.emit({ width: el.offsetWidth, height: el.offsetHeight });
      }
    });
  }

  @HostListener('document:mouseup')
  onMouseUp(el) {
    this.ngOnDestroy();
  }

  constructor(private renderer: Renderer2) {}

  ngOnDestroy() {
    if (this.mouseMoveListener) {
      this.mouseMoveListener();
    }
  }
}

Use it as follows:

<textarea (resize)="resizeEvent($event)"></textarea>

Stackblitz Example



回答2:

This will fire a few extra events, but should work:

<textarea rows="4" cols="40" #ta 
    (mousemove)="$event.buttons === 1 ? updateSize(ta.clientHeight, ta.clientWidth) : null">
</textarea>

see also https://stackoverflow.com/a/526352/217408

or maybe even better:

<textarea rows="4" cols="40" #ta 
    (mouseup)="updateSize(ta.clientHeight, ta.clientWidth) : null">
</textarea>

see also https://stackoverflow.com/a/10218286/217408