【问题标题】:Angular : how to set a conditional clear button for a textareaAngular:如何为文本区域设置条件清除按钮
【发布时间】:2020-12-22 02:38:33
【问题描述】:

在我的 Angular 应用中

我有一个包含文本区域的表单

我的建议是在 textarea 元素中添加一个清除按钮,即清除按钮:

  • 应仅在 texarea 聚焦时出现
  • 当文本区域失焦时应该消失(单击 outisde)
  • 单击时应清除文本区域内写入的文本

我已经这样做了:

<form [formGroup]="form">
    <p>This is a reactive form<br />
        <textarea (focusin)="componentMethod($event)" (focusout)="onfocusout($event)" formControlName="test" #test ></textarea>
        <button  *ngIf="showNotes" type="reset" id="close-resetNotes" class="close" aria-label="Close" (click)="resetNotes()">
    <span aria-hidden="true">×</span>
  </button>
    </p>
</form>

在 ts 部分:

export class AppComponent {
  public form: FormGroup;
  showNotes = false;
  @ViewChild("test") textareaElement: ElementRef;

  constructor(private formBuilder: FormBuilder) {}

  public ngOnInit() {
    this.form = this.formBuilder.group({
      test: ["some text", Validators.nullValidator]
    });
  }

  public componentMethod(event) {
    this.showNotes = true;
  }

  public onfocusout(event) {
    this.showNotes = false;
  }

  resetNotes() {
    this.form.patchValue({ test: "" });
    this.showNotes = true;
  }
}

问题在于,当单击清除按钮时,文本区域甚至在应用 onClick 清除按钮操作之前就已聚焦

建议??

【问题讨论】:

  • 这里有什么问题?如果单击其他元素,则当前焦点将更改。那应该没问题。不过,您的点击处理程序应该被调用。不是吗?
  • 不要认为 setimeout 是一个很好的选择..没有更好的方法吗?

标签: javascript html angular typescript angular-forms


【解决方案1】:

您可以使用 textarea 的 focusblur 事件和变量来相应地设置条件。 我根据您的要求创建了一个示例代码,看看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多