清除Angular2中的输入文本字段 [英] Clearing an input text field in Angular2

查看:82
本文介绍了清除Angular2中的输入文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我尝试清除文本字段时此方法不起作用?

Why is this method not working when I try to clear the text field?

<div>
      <input type="text" placeholder="Search..." [value]="searchValue">
      <button (click)="clearSearch()">Clear</button>
</div>


export class App {
  searchValue:string = '';
  clearSearch() {
    this.searchValue = '';
  }
}

我期望的是:由于我传递了一个用于搜索值的属性,因此当我单击按钮时,它应该获得在clearSearch()函数中处理的更新后的值.

What I'm expecting: since I'm passing a property for search value, when I click the button, it should get the updated value which is processed in clearSearch() function.

我还注意到,如果将默认值设置为searchValue,则clearSearch()函数有效,但只能运行一次.

I also noticed that if I set a default value to searchValue, clearSearch() function works, but only once.

检查我的朋克车.

推荐答案

1.第一种方法

您必须在此处分配空字符串或空字符串

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

工作柱塞

因为角度变化检测没有触发任何事件.因此您必须分配一些值为null或带空格的字符串

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

  • 使用[(ngModel)]应该可以与ngModel一起使用.
  • use of [(ngModel)] it should work with ngModel.

为什么?

why ?

因为与使用value属性进行绑定一样,该属性仅是属性绑定而不是事件绑定.所以 由于不会触发与Angular相关的事件,所以angular不会运行更改检测.如果您绑定到事件,则Angular会运行更改检测,并且绑定有效且值应该更改.

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

查看与ngModel相同的工作示例

使用ngModel的示例

这篇关于清除Angular2中的输入文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆