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

Loop through a collection of map instances in TypeScript

In my TypeScript code, I am making a call to an API method in a Java class that returns a list of maps. The TypeScript file includes the code snippet below. When attempting to retrieve data from dataBody, it displays as [Object Object]. I need assistance ...

Exploring Angular: Retrieving a Variable in TypeScript Using a String Passed from HTML

Is there a way to retrieve the value of a variable in .TS by passing its name as a string from HTML? For example: In HTML: <div id="myID"><button mat-button (click)="foo('name')">Export to Excel</button></div> In TS v ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

What is the correct way to utilize window.scrollY effectively in my code?

Is it possible to have a fixed header that only appears when the user scrolls up, instead of being fixed at the top by default? I've tried using the "fixed" property but it ends up blocking the white stick at the top. Adjusting the z-index doesn&apos ...

Using a union type annotation when passing into knex will result in the return of an unspecified

Knex version: 2.5.1 Database + version: postgres15 When passing a union typescript definition into knex as a type annotation, it returns the type any. However, by using type assertion as UserRecord, we can obtain the correct UserRecord type. It is my un ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

How to Retrieve Observable<Record<string, boolean>> Value with the Help of AsyncPipe

My service retrieves permissions for the currently logged-in user as a record. The necessary observable is declared in my TypeScript file as a member variable: permissionsRecord$: Observable<Record<string, boolean>>; When I call the service, ...

The process of incorporating the dymo.framework into an Angular project

My Angular project is currently in need of importing dymo.connect.framework. However, I am facing some challenges as the SDK support provided by dymo only explains this process for JavaScript. I have also referred to an explanation found here. Unfortunate ...

Avoiding duplicate subscriptions in Angular 4/5: a guide to streamlining

I'm looking for a streamlined way to capture a query parameter and subscribe to an API in order to retrieve results. Currently, I am using combineLatest but it seems a bit excessive. Is there a more efficient approach that focuses solely on the queryP ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...

Learning how to smoothly navigate to the top of a page when changing routes in Angular using provideRouter

Is there a way to make the Angular router automatically scroll to the top of the page when the route changes? In my previous setup using NgModules, I could achieve this with: RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'top' }) ...

Challenge with Angular dependencies: Transitioning from Windows to Linux

I'm facing a challenge with hosting an Angular application on Linux for a client. The application runs smoothly on Windows where the customer develops it. My NodeJS version is 19. Upon running npm install, I encountered this error message: npm notice ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

What is the process for implementing a pipe to establish data binding?

I've been trying to use a pipe for data binding in Angular, but it's not working as expected. Previously, I had this: [message]="enum.text" and now I want to replace enum.text with a custom pipe. Here's what I tried: [text]=" '' ...

Error in Angular 7 Reactive Forms: "No value accessor available for form control without a specified name attribute"

I'm encountering issues with some form fields while using reactive forms in Angular. Any insights on why this might be happening would be greatly appreciated. Just started working with Angular and Material 7, if that's relevant. An interesting ...

"Transform the appearance of the datepicker input field with Material 15's dynamic

I am in need of assistance to change the color to white for the input date and add an underline to a datepicker element <mat-form-field class="date-criteria-select " [floatLabel]="'always'"> <mat-label class=" ...

Customize the theme type with @mui/system

Is there a way to customize my theme settings in @mui/system? While using the sx prop in Stack, the theme is defined in createTheme.d.ts, but it seems like there isn't an option to extend or override it. To work around this limitation, I have been u ...

The main module's postinstall process is initiated before the sub-module's postinstall process

Update: I am seeking guidance on how to install a module from GitHub instead of npm. That's the main query. In case you're wondering why: I'm currently working on some confidential projects and prefer not to publish the code. As a result, ...

I'm getting errors from TypeScript when trying to use pnpm - what's going

I've been facing an issue while attempting to transition from yarn to pnpm. I haven't experimented with changing the hoisting settings yet, as I'd prefer not to do so if possible. The problem lies in my lack of understanding about why this m ...