Angular 13: Sending a delete request to the API with additional effects

I am currently working on a front-end application that is connected to a back-end system. Everything seems to be functioning well, but I have encountered an issue where deleting a div with a post causes it to disappear without any visual effect. I would like to add some animation or effects to make it clear to the user that the post has been deleted. Although I am new to Angular and this is my first front-end app, I believe it should be a simple task to accomplish.

Below is the code for the method used to delete a post:

deletePost1(id:number){
    this.messageService.delete(id).subscribe(res => {
      this.messages = this.messages.filter(item => item.id !== id);
      console.log('Post deleted successfully!');
    })
  }

And here is the corresponding method in the service:

delete(id: number) {
    return this.httpClient.delete(this.apiURL + 'api/message/' + id, this.httpOptions)
      .pipe(
        catchError(this.errorHandler)
      )
  }

Answer №1

If you want to show a notification using the ngx-toaster library:

Start by installing the package via npm :

npm install ngx-toastr

Next, incorporate it into your app.module.ts file:

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { ToastrService } from 'ngx-toastr';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot({
      tapToDismiss: false,
      autoDismiss: true
    })
  ],
  providers: [
    ToastrService
  ],
  bootstrap: [AppComponent],
  schemas: []
})
export class AppModule { }


Then create a deletePost() method in your component like this :

constructor(
    private toastr: ToastrService
  ) { }

deletePost1(id:number) {
    this.messageService.delete(id).subscribe(res => {
        this.messages = this.messages.filter(item => item.id !== id);
        this.toastr.success("Post deleted successfully!", 'success', { timeOut: 2500 });

    })
}

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

Establishing reducers within Ngrx

I'm currently in the process of setting up a basic Ngrx state management system. # app.module StoreModule.forRoot(reducers), This particular code snippet has been automatically generated using the Ngrx schematics generators. export const reducers: Ac ...

Troubleshooting issues with unit testing a component that utilizes a mocked service

I recently delved into testing Angular components and services. After watching a course on Pluralsight, I tried implementing some ideas from the tutorial available at . Unfortunately, I encountered an issue with testing the component method. Despite my eff ...

Guide on transforming this Formik snippet into Typescript code without errors

https://i.sstatic.net/DcEvx.png Can someone please guide me on passing the values: onSubmit={(input, { setSubmitting, resetForm }) into a function within formik code. Also looking for ways to resolve this warning: https://i.sstatic.net/isJxi.png Your ...

Angular issue: Readonly or disabled input fields not submitting data

Struggling with creating a form in Angular 2 to submit dynamically generated values from a service. The goal is to calculate the equivalent amount of bitcoin for X chilean pesos using Angular's http module to fetch the price. However, facing an issue ...

How should dynamic route pages be properly managed in NextJS?

Working on my first project using NextJS, I'm curious about the proper approach to managing dynamic routing. I've set up a http://localhost:3000/trips route that shows a page with a list of cards representing different "trips": https://i.stack. ...

Exploring the Possibilities of Retrieving an Array within an Object in Angular 2

After retrieving this array from my database : https://i.sstatic.net/OKrCH.png This function is used to fetch the data : getMembers(){ this.db.list(`projects/${this.auth.userId}/${this.uploadService.pro.name}/teams/`).snapshotChanges().pipe( map( ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

"Utilizing provideMockStore in NgRx 8 for setting the state of a specific State Slice

I have been working on testing a smart component for my NgRx implementation, and the test setup looks like this: describe( 'Component', () => { let store: MockStore<State>; beforeEach( async( () => { TestBed.configureTesting ...

Searching through the entirety of a meteor for text can yield valuable information. Once a client subscribes to the search

Trying to implement a full text search feature in Meteor with Angular 2. Here is my publish function: Meteor.publish("search", (searchValue) => { console.log(searchValue); if (searchValue) { return Nutrition.find( {$text: ...

Include method in NodeJs console utilizing TypeScript

I implemented a new function called red in Node's console. Now, the question is how to make TypeScript aware of it? import chalk from "chalk"; const red = (text: unknown[]) => chalk.red(...text); console["red"] = red; I have att ...

Exciting News!! Angular 10 Update: Detecting a Circular Dependency When Injecting a Service into a Specific Module. What Sets @Inject Apart from providers[ ]?

I'm trying to integrate my countries.service into my pricing.module and utilize it within the list-pricing component of that module. However, I encountered a circular dependency issue. https://i.sstatic.net/iNepg.jpg This is how my module looks like ...

Vue 3 components array typified with Typescript

I'm attempting to establish an array of components representing various steps. Initially, I attempted to assign the type to these steps: const steps = ref<Component[]>([ Component1, Component2, Component3, ]); However, this approach is n ...

Double curly brace Angular expressions being repeatedly evaluated during mouse click events

Within our Angular application, the code structure is as follows: <div>{{ aGetProperty }}</div> <div>{{ aMethod() }}</div> Upon clicking anywhere on the page, these expressions are being evaluated repeatedly. For example, if there ...

What is the reason for the `Function` type not functioning properly when trying to input a function as a parameter in a higher-order function?

Looking to create a function that requires the following inputs: an array a filter logic function (predicate function) In JavaScript, you can use the following code successfully: const myFilter = (func, arr) => arr.filter(func) const myArr = [1, 2, 3, ...

"Utilize ngClass to dynamically update the styling of elements

Hello, I've encountered an issue with a basic Angular component. I'm using a reactive form to input text and then displaying the text using ngFor loop. However, when I try to set one element as active on click, all elements end up with the active ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

What might be causing my observable to fail to return a value?

I'm currently utilizing an API known as ngx-pwa localstorage, which serves as a wrapper for an indexeddb database. Within my Angular project, I have a service that interacts with this database through a method called getItem: getItem(key: string) { ...

Having trouble getting `npm install ngx-contextmenu @angular/cdk` to work properly with Angular 11?

After creating a project using "ng new proj", I encountered an issue when trying to install ngx-contextmenu and @angular/cdk. The npm installation failed with the following error message. Any suggestions on how to resolve this? I attempted to update to @an ...

Implement tooltip functionality in ssr chart using echarts

A chart is generated using echarts on the server-side: getChart.ts const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 400, height: 300 }); chart.setOption({ xAxis: { data: timeData }, ...

Utilizing the drag-and-drop feature within a virtual machine's clarity tree

I am currently working on an Angular application that utilizes the Clarity framework. Within this application, we have implemented a Tree component to showcase a list of items, which is functioning properly. However, we are interested in enabling the abili ...