Surya
Surya

Reputation: 546

Clear the input box after submitting the form in Angular 4

I want to clear the input box after submitting the form.

this is my app.component.ts file:

todos: string[];

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

this is my app.component.html file

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

When I fill a todo in my input box, and press enter or return key on my keyboard it should automatically clear my input box.

Upvotes: 1

Views: 4862

Answers (2)

DeborahK
DeborahK

Reputation: 60596

You can use data binding.

The HTML would then look like this:

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

Be sure to pull in the FormsModule now that we are using two-way binding.

The class would look like this.

todos: string[];
currentTodo: string

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

You could even use currentToDo in the addTodo function instead of passing it in:

todos: string[];
currentTodo: string

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

Here is the change to your AppModule that you'll need for two-way binding:

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

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

Upvotes: 1

Darshita
Darshita

Reputation: 746

In app.component.ts file change the follwing code :

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;
   }
}

By using this,after submitting the form textbox value will be cleared.

Hope, it wil help!

Upvotes: 7

Related Questions