Updating an array by adding or removing items

I am attempting to create a method for deleting and adding items to an array, but I need easy-to-use delete and add methods since I am unfamiliar with TypeScript.

export class NgForComponent implements OnInit {

  Numbers: number[];
  constructor() {
    this.Numbers = [1, 2, 3, 4, 5];
   }

  ngOnInit() {
  }

}

HTML

        <div>
    <ul>
        <li *ngFor="let number of Numbers">
          {{number}}
        </li>
    </ul>


    </div>

    <button >Delete</button>

Answer №1

 <li *ngFor="let number of Numbers;let i = index">
          {{number}}
  <button (click)="removeNumber(i)">Remove</button>
 </li>

 in typescript
removeNumber(i){
   this.Numbers.splice(i,1);
}

Answer №2

To ensure you are deleting the correct item, you must include the delete function within the ngFor loop. Alternatively, you can modify your interface to clearly identify which item should be deleted.

<ul>
 <li *ngFor="let number of Numbers">
          {{number}}
  <button (click)="delete(number)">Delete</button>
 </li>
</ul>

In your Typescript file:

delete(item: any){
   this.Numbers.splice(item, 1);
}

Answer №3

<ul>
 <li *ngFor="let number of Numbers">
          {{number}}
  <button (click)="remove(number)">Remove</button>
 </li>
</ul>

and the corresponding typescript code

remove(number){
this.Numbers.filter(num => num !== number)
}

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

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

Encountered an issue while attempting to assign a value to a property that is declared as [key in keyof T]

I am currently working on implementing a function that selects specific properties of an object. Here is the current function: const project = function<T>(object: T, projection: Projection<T>): Partial<T> { throw new Error("not imple ...

Sign up for the category that failed to assign a worth

Currently, I have a service that includes a getter and setter: // Service import { Subject } from 'rxjs'; export class MyService { public currentUser: any = new Subject(); ... there is a function where I call setCurrent and assign value ...

utilize switchMap to terminate an HTTP request within an ngrx effect

Behold the ngrx effect in question: @Effect() throwError$: Observable<Action> = this.actions$.pipe( ofType<notificationActions.ErrorThrow>( notificationActions.ActionTypes.ThrowError ), tap(() => { this.store.dispa ...

Executing additional code after all tests have finished in Mocha.js

In the world of MochaJS testing, it is customary to have before and after blocks for setup and teardown operations. But what if we want to execute an extra cleanup step after all test files have been processed? This is crucial to ensure that any lingering ...

When attempting to run npm install -g @angular/cli, there are no valid versions found for the undefined package

Currently operating on Windows 10 Enterprise. I am attempting to install Angular CLI for running an Angular project. I have input the following command. --> npm install -g @angular/cli Unfortunately, I encountered the following error. --> npm E ...

The functionality of Angular 4 routing breaks down when attempting to access a direct URL path

Currently, I am working on an Angular 4 application that has numerous routes. The issue I am encountering is fairly straightforward to comprehend. All routing functions as expected within the app; however, a problem arises when accessing a specific URL dir ...

Is there a way for a dialog to prompt a Parent Window to refresh its grid?

My Angular Material Grid has an Edit option that opens a form using mat-dialog when clicked. Upon trying to close the form, another dialog prompts the user to save the changes made. If the user chooses to save, the data is sent to the backend via API and b ...

Is there a similar function to $.ajax for React.js and Angular.js?

Can you guide me on how to send data using both React and Angular? Is there a similar function to $.ajax in React and Angular frameworks? I am looking for a post function that works like the one shown below in both React and Angular: $.ajax{ url:"test.p ...

tips for replacing multiple route parameters in Angular using the replace function

I am facing an issue when trying to replace multiple parameters using the angular replace function. The problem is that the function only detects the first parameter. For example, if I have this route admin/management/{type}/card/{id}, and use the route.r ...

What is the best way to ensure the hamburger menu stays perfectly centered?

My menu is currently aligned to the right and scrolls with the user profile. I want the menu to always be centered and the profile to stay on the right side. I am working with Angular 12 and Bootstrap 5 for this project. Here is the code I have been usin ...

Angular - combining lowercase letters in an attribute

Hello, I'm new to using Angular and currently working on creating an attribute within a div tag. I have successfully achieved this task. However, I am in need of changing my input to lowercase during the concatenation. <!--"Fade" Slider--> < ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Transform a Typescript type that includes multiple string options into an array containing those options as values

Sending Status: const statusArray = ["confirmed", "pending", "canceled"] Purpose: While the type is automatically generated, I also require it to be in array form. ...

"Angular throws an error code NG5002 when encountering an invalid ICU message along with an unexpected

Currently, I'm utilizing the most recent release of Angular 17.0.0-next.6, which introduces support for the updated control flow. Interestingly, individuals on Twitter have mentioned that it works flawlessly for them; hence, the issue likely resides w ...

What could be causing the sluggish performance of my protractor test cases?

I'm a beginner with Protractor. Utilizing Protractor and Jasmine for end-to-end automation testing on an Angular4 application. Noticed that when running a specific suite, it performs quickly. However, running all suites takes considerably longer to fi ...

The form doesn't seem to be functioning properly when I incorporate the formgroup and service within the ngOnInit() method

I implemented the formgroup code in ngOnInit() and also utilized a service in ngOnInit(). However, the asynchronous nature of the form is causing issues. The full code on StackBlitz works when I use dummy JSON data within the constructor. Check out the wor ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Encountered issue with deploying Angular app to Firebase platform

After attempting to deploy my Angular 4 application on Firebase, I noticed that the setup process did not prompt me for any configuration details as outlined in various resources online. Despite running the 'firebase init' command and only being ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...