Clear the input field once an item has been successfully added to the array

I'm working on a CRUD application using an array. Once I add an item to the array, the HTML input field doesn't clear or reset. I've searched online but couldn't find a reset method in Angular. How can I clear the input field after adding an item?

Here's the code snippet:

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

If you have any suggestions or solutions, please share them. Thank you!

Answer №1

When working with Angular forms, the reset() method is typically used in reactive forms. However, if you are not using a reactive form, you can still reset the input field by changing your method to:

(click)="create(item.value); item.value = ''"

If your form is complex and requires more functionality, it is recommended to use reactive forms. In this specific example, the current approach you are taking is suitable.

You can view a working example here.

Answer №2

It appears that you have included the information here

  addNewItem() {
    this.list.push({
      item: ''
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the length of the current items in a shopping cart using Angular and RxJS in my template for an ecommerce website

I am trying to create a counter for the number of items in my shopping cart. This counter will be displayed on my home page using Angular 9. I have a function that returns the current number of items in my shopping cart, and I want to display this value i ...

Utilizing a component from a different module

Currently working on Angular 4 and facing an issue with referencing a component from another module. In my EngagementModule, the setup is defined as below: import { NgModule } from '@angular/core'; // other imports... @NgModule({ imports: [ ...

Is there a way to adjust the height of mat-sidenav-content to be 100%?

I'm having trouble scrolling down my mat-sidenav-content to reach the bottom where my pagination is located. When I try using fullscreen on mat-sidenav-container, my mat-toolbar disappears. How can I adjust my mat-sidenav-content based on the content? ...

Tips for fixing the error "Module cannot be found" when testing Typescript in a Github Action

Whenever I use the Github Actions Typescript template to create a new repo and then check it out locally, I face a recurring issue: While I can work on the source code in VS Code without any problems and follow the steps mentioned in the template's re ...

What sets the do/tap operator apart from other observable operators?

Can anyone clarify the distinction in simple terms between the typical observable operators used for observing output and why do/tap appear to serve the same purpose? What is the reason for utilizing do/tap? ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

gulp-angular2 task is malfunctioning

Currently, I am in the process of working on a gulpfile and have written the following task: var tsProject = ts.createProject('app/Resources/public/angular/tsconfig.json'); gulp.task('angular-2', function () { var tsResul ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Angular 2's subscribe method allows for actions to be taken in response to

There are two buttons, one of which is hidden and of type file. When the user clicks the first button, a confirmation dialog opens. Upon clicking "Ok" in the dialog, the second button should be clicked. The issue arises when all the logic in the subscribe ...

Node for Angular forms workflow

I'm on the hunt for workflow nodes with forms that open when the user clicks on them. While I've come across a few options, not all of them are open source. Can you point me towards some open source (simple and basic) alternatives? Here's w ...

ParcelJS takes a unique approach by not bundling imported JavaScript libraries

My NodeJS app, which is a Cloudflare Worker, seems to be having trouble with bundling the 'ping-monitor' dependency. In my main typescript file (index.ts), I import the handler module and the first line reads: const Monitor = import('ping-m ...

Issue with installation of Npm package dependencies

I recently created an npm package from a forked repository at https://github.com/pwalczak83/angular2-datatable After changing only the name and version in the package.json file, I installed the package using npm i -S angular2-datatable-custom. However, up ...

Unable to use 'ngFor' as it is not recognized as a property of ... in a mixed AngularJS and Angular environment

My AngularJS and Angular hybrid application is giving me trouble when I try to downgrade my Angular test.component. Every time I attempt it, I encounter the following error messages: Can't bind to 'ngFor' since it isn't a known pro ...

Preserving type information in TypeScript function return values

Wondering how to make this code work in TypeScript. Function tempA copies the value of x.a to x.temp and returns it, while function tempB does the same with x.b. However, when calling tempA, the compiler seems to forget about the existence of the b field ...

ESLint refuses to be turned off for a particular file

I am in the process of creating a Notes.ts file specifically for TypeScript notes. I require syntax highlighting but do not want to use eslint. How can I prevent eslint from running on my notes file? Directory Structure root/.eslintignore root/NestJS.ts r ...

Utilize React.useImperativeHandle() for declaring custom types

function App(){ const refEl:React.MutableRefObject<any> = React.useRef(null); // I am uncertain about the appropriate type here. React.useEffect(()=>{ if(refEl.current){ refEl.current.start() } }, []); return <Countdown ref={refEl} ...

Angst with the Angular Command Line Interface

After installing the Angular CLI via the command prompt, I encountered an error related to @angular-devkit/build-angular. However, everything else seems to be working fine. Does anyone have any ideas as to why this might be happening? https://i.stack.im ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

What method can be utilized to selectively specify the data type to be used in TypeScript?

Currently, I am facing a scenario where a certain value can potentially return either a string or an object. The structure of the interface is outlined as follows: interface RoutesType { projects: string | { all: string; favorite: string; cr ...