首页 > 解决方案 > 当我从 textarea 中删除所有内容时,如何触发函数?

问题描述

要重现问题,请在文本区域内输入文本,直到它展开。展开后,选择所有文本并点击删除。

预期的结果是文本区域应该缩小(如果你再次按下一个键它会缩小)但实际上什么也没发生。

我已将所有可能的事件附加到文本区域

Stack Blitz 示例 (最小、完整和可验证的示例。)

    import { Component, Input, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
      <textarea class="commentText"
              cdkFocusInitial
              #commentTextArea
              [style.height]="textAreaHeight"
              (keyup)="textAreaResize()"
              (keydown)="textAreaResize()"
              (keypress)="textAreaResize()"
              (change)="textAreaResize()"
              (input)="textAreaResize()"
              (focus)="textAreaResize()"
              [maxLength]="300"
              [(ngModel)]="commentTextValue"
              placeholder="Type your Comment">
    </textarea>

  `,
  styles: [`
  .commentText {
  width: 300px;
  min-height: 59px;
  max-height: 100px;
  //height: 59px;
  border-radius: 4px !important;
  border: solid 1px #bab8b8 !important;
  //text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
  font-size: 13px;
  color: #000000;
  padding: 6px;
  resize: none;
}
  `]
})
export class HelloComponent {

  commentTextValue: string;
  textAreaHeight: any;

  @ViewChild('commentTextArea', { static: false }) commentTextArea: ElementRef;

  constructor(private changeDetectorRef: ChangeDetectorRef
  ) {
  }

  textAreaResize() {
    this.changeDetectorRef.detectChanges();

    const textArea: HTMLTextAreaElement = this.commentTextArea.nativeElement;

    // console.log('textArea.scrollHeight', textArea.scrollHeight);

    if (this.commentTextValue) {
      if (this.commentTextValue.length < 107) {
        this.textAreaHeight = '59px';
      } else {
        const height = Math.max(57, Math.min(textArea.scrollHeight, 98));
        textArea.style.overflow = (textArea.scrollHeight > height ? "auto" : "hidden");

        this.textAreaHeight = height + 'px';
      }
    }



  }



}

标签: angular

解决方案


您添加了一个检查if (this.commentTextValue),当您删除所有文本时,它不会得到满足。

添加条件|| this.commentTextValue == ""

像这样:

if (this.commentTextValue || this.commentTextValue == "")

工作堆栈


推荐阅读