【问题标题】:html textArea resize event with Angularhtml textArea使用Angular调整大小事件
【发布时间】:2018-04-19 21:50:09
【问题描述】:

我有一个类似行的布局,在行上,嵌入的 div 中有几个文本区域,如下所示:

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

如果用户使用小三角形按钮调整 textArea 的大小,我需要相应地调整当前行高(和其他属性)。我在jQuery 中找到了一些解决方案,但我只需要坚持使用 Angular 指令。

演示: http://jsfiddle.net/o0yvysL5/1/

最好,我需要某种可以订阅的事件,例如&lt;textarea (resize)="resizeEvent($event)" ...,但没有。

有什么想法吗?

【问题讨论】:

    标签: javascript html angular


    【解决方案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();
        }
      }
    }
    

    如下使用:

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

    Stackblitz Example

    【讨论】:

    • 这是一个非常好的解决方案!不过一件小事。使用 Google Chrome 版本 59.0.3071.115(官方构建)(64 位)我可以通过快速鼠标拖动 screenshot 来生成它。在这里,容器 div 的高度(绿灰色车道)设置为最后发出的值。最后一次发射仍然显示高度为 67,尽管 textarea 本身现在更小了(只有 24 像素)。我只能在极端情况下重现它,(向下移动鼠标,然后快速向上,越过 textarea 本身)
    【解决方案2】:

    这会触发一些额外的事件,但应该可以:

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

    另见https://stackoverflow.com/a/526352/217408

    或者甚至更好:

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

    另见https://stackoverflow.com/a/10218286/217408

    【讨论】:

    • 问题是这在以下情况下不起作用: 1. 用户单击并开始拖动三角形 2. 用户将拖动移到 textArea 之外 3. 由于 textArea 不能水平增长,鼠标会移到元素外 4.当用户在外,或者在textArea外释放点击时,不会调用任何事件。
    • 另外,对我来说,如果你点击 textArea 会触发 mouseup 和 mousemove 事件,但不会触发角上的三角形。
    • 这很可悲 :-/ .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2018-12-13
    • 2013-06-22
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多