Angular4中提交表单后清空输入框

Clear the input box after submitting the form in Angular 4

我想在提交表单后清除输入框。

这是我的 app.component.ts 文件:

todos: string[];

addTodo(todo)
{
   this.todos.push(todo);
   return false;
}

这是我的 app.component.html 文件

<form (submit)="addTodo(todo.value)">
<input type="text" #todo>
<ul>
<li *ngFor="let todo of todos">{{todo}}</li>
</ul>

当我在输入框中填写待办事项,然后按回车键或键盘上的 return 键时,它应该会自动清除我的输入框。

您可以使用数据绑定。

HTML 看起来像这样:

<form (submit)="addTodo(todo.value)">
<input type="text" #todo [(ngModel)]="currentToDo" name="todo">
<ul>
<li *ngFor="let todo of todos">{{todo}}</li>
</ul>

既然我们正在使用双向绑定,请确保引入 FormsModule。

class 看起来像这样。

todos: string[];
currentTodo: string

addTodo(todo)
{
   this.todos.push(todo);
   this.currentTodo = '';
   return false;
}

您甚至可以在 addTodo 函数中使用 currentToDo 而不是传入它:

todos: string[];
currentTodo: string

addTodo()
{
   this.todos.push(this.currentTodo);
   currentTodo = '';
   return false;
}

以下是双向绑定所需的 AppModule 更改:

import { NgModule } from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ]
})
export class AppModule { }

app.component.ts 文件中更改以下代码:

import { Component,ViewChild,ElementRef } from '@angular/core';
export class AppComponent {

   @ViewChild("todo") el : ElementRef
   addTodo(todo)
   {
       this.todos.push(todo);
       this.el.nativeElement.value = "";
       return false;
   }
}

通过使用这个,提交表单后文本框的值将被清除。

希望对您有所帮助!