I am creating a crud app using an array. After I add a item to the array, the html input field does not clear/reset. I dont think angular has a reset method because I could not find anything online. How can I clear the input field after adding an item?
Here is my code:
app.component.html
<div class="container">
<div class="jumbotron text-center">
<h1>Angular CRUD</h1>
</div>
<div class="container">
<form class="form-inline custom-centered" name="itemForm">
<label for="item">Add an Item:</label>
<input type="text" class="form-control" name="Value" id="Value" #item>
<button type="submit" class="btn btn-success" (click)="create(item.value)" style="width: 80px;">Add</button>
</form>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of collection">
<td>{{item.name}}</td>
<td>
<button class="btn btn-info btn-sm mr-1">Edit</button>
<button (click)="deleteItem(item)" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
</tbody>
</table>
app.component.ts
export class AppComponent {
collection: any = [];
create(item: any) {
this.collection.push({
name: item
});
}
deleteItem(item: any) {
this.collection.splice(item, 1);
}
}
Can anyone guide me please, Thank you
CodePudding user response:
Angular has reset() method in reactive forms. But here you are not using reactive form, so here the way to reset the input is, replace your method with this -
(click)="create(item.value); item.value = ''"
If your form is large, then reactive form is recommended. In this example, what you are using is fine.
CodePudding user response:
I think you wrote it in there
create() {
this.collection.push({
name: ''
});
}