user944513 user944513 - 6 months ago 64
AngularJS Question

how to clear input field after pushing item on array?

I made a simple example of angular 2. I added item in an array. When user types anything and press the button, it is added into the array and get displayed in the list .

I am facing two issues


  • 1 ) how to clear input field after pusing to array ?

  • 2 ) How angular 2 works ? As in document Angular 2 remove watches .So
    when item is added in array .how template show updated list .how ?

    is it watching the model of list ?



Here is my plunker code

<ion-navbar *navbar>
<ion-title>
Ionic 2
</ion-title>
</ion-navbar>

<ion-content class="has-header">
<ion-list style="border:2px solid grey;height:500px">
<ion-item *ngFor="#item of Todo">
{{item.name}}
</ion-item>
</ion-list>
<label class="item item-input">
<span class="input-label" >Add Todo</span>
<input type="text" #todo placeholder="Add todo" >
</label>
</ion-content>

<ion-footer-bar (click)="addItem(todo.value)">

<h1 class="title" style='color:red'>Add Todo!</h1>

</ion-footer-bar>

Answer

You can clear the input fields by doing the following things.

Home.html

previous code

<ion-footer-bar (click)="addItem(todo.value)">

  <h1 class="title" style='color:red'>Add Todo!</h1>

</ion-footer-bar>

changed code

<ion-footer-bar (click)="addItem(todo)">

  <h1 class="title" style='color:red'>Add Todo!</h1>

</ion-footer-bar>

Modify the addItem function in home.ts like below.

addItem(v){
      this.Todo.push({name:v.value})
      v.value='';
    }

Hope this gives you a solution for the problem you faced. There are so many other ways too. Since you get the value from the id, I have given the solution based on that.

updated plunker code below

http://plnkr.co/edit/oCxrgxNlCkjVnTrhZGQA?p=preview