How can I use Angular to change the background color of an element with the tag "li

I am working on a to do app using Angular. The data for the app is sourced from https://jsonplaceholder.typicode.com/todos. My goal is to have the background color of a "li" change when the Done button is pressed. Can anyone help me with implementing this feature?

Below is the Html code:

<input
  (keyup.enter)="createPost(title)" #title
  type="text" class="form-control">
<ul class="list-group">
  <li
  *ngFor="let post of posts"
  class="list-group-item">
  <button
    (click)="updatePost(post)"
    class="btn btn-success btn-sm" id="button">
    {{post.completed ? 'Done' : 'Not ready'}}
  </button>
  <button
    (click)="editPost(post)"
    class="btn btn-dark">
    Edit
  </button>
  <button
    (click)="deletePost(post)"
    class="btn btn-danger">
    Delete
  </button>
  {{ post.title }}
  </li>
</ul>

Here is the update function for reference:

  updatePost(post) {
    this.http.patch(this.url + '/' + post.id, JSON.stringify({ completed: !post.completed })).subscribe(response => {
      post.completed = !post.completed;

    });
  }

Answer №1

Utilize ngClass to dynamically apply a class depending on the post status

<input
  (keyup.enter)="createPost(title)" #title
  type="text" class="form-control">
<ul class="list-group">
  <li
  *ngFor="let post of posts"
  [ngClass]="post.completed?'list-group-item list-group-item-success':'list-group-item'">
  <button
    (click)="updatePost(post)"
    class="btn btn-success btn-sm" id="button">
    {{post.completed ? 'Done' : 'Not ready'}}
  </button>
  <button
    (click)="editPost(post)"
    class="btn btn-dark">
    Edit
  </button>
  <button
    (click)="deletePost(post)"
    class="btn btn-danger">
    Delete
  </button>
  {{ post.title }}
  </li>
</ul>

Answer №2

Utilize ngClass to change the styling of list items based on a condition. The syntax for this is [ngClass]="{'highlight-post': post.completed}"

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

Saving a picture to your Ionic device

I am currently using the code snippet below to access the device's Photo Library. However, it is returning a base64 encoded string, which has left me feeling unsure of how to proceed with this information. My goal is to save the photo to the applicati ...

Oops! An unhandled promise error occurred when trying to fetch a URL with a status of 0. The response received has a status code of

I keep encountering an error whenever I try to hit a post request URL: Error: Uncaught (in promise): Response with status: 0 for URL: null at c (http://localhost:8100/build/polyfills.js:3:19752) at c (http://localhost:8100/build/polyfills.js:3:1 ...

Contrast between utilizing form data versus base64 encoding for transmitting images to a .NET API

Currently tackling an angular 2 project where I need to transmit images along with data to a .NET Core API. How can this be accomplished effectively? Utilizing a cropper that produces base64 output. In previous requests, sending a single image as for ...

Sequencing API Calls: A Guide on Making Sequential API Requests

Currently, I am working on mastering RxJS. Within my project, there are 3 API calls that need to be made. Specifically, I must execute the 2nd API call and then pass its data as a parameter to the 3rd API call. My attempt at achieving this functionality is ...

Exploring Angular route navigation functionality without utilizing an outlet

Currently, I am in the process of creating a specification document for an Angular component that contains a button used for navigating to another page. The component relies on Router::navigate() function but does not have its own router outlet; instead, i ...

Adjust cursor location in a provided OnTypeFormattingEdits with Monaco Editor

I've implemented the following code to automatically close an XML tag when typing the '>' of an opening tag. Everything is working smoothly so far, however, I am trying to position the cursor between the tags instead of at the end of the ...

An error occurs when attempting to access a property that does not exist on type 'never'. Why is this considered an error rather than a warning?

I am experiencing an issue with the following code snippet: let count: number | undefined | null = 10; count = null; let result: string | undefined | null = count?.toFixed(2); console.log(`Result: ${result}`); The error message I received is as follows: ...

Encountering a 'scheduler flush execution error' and an Uncaught TypeError due to VueJS and Axios integration

After carefully examining my code, I have pinpointed the cause of this error to the following line: treeNodes.value = documentStore.convertToTree((await axios.get('/File')).data); Initially, I receive a warning: Vue warn]: Unhandled error during ...

When utilizing the Map.get() method in typescript, it may return undefined, which I am effectively managing in my code

I'm attempting to create a mapping of repeated letters using a hashmap and then find the first non-repeated character in a string. Below is the function I've developed for this task: export const firstNonRepeatedFinder = (aString: string): strin ...

Working with an arbitrary number of arguments in TypeScript

Looking for a way to pass an arbitrary number of arguments with different types into a function and utilize those types, similar to the following: function f<A>(a: A): A; function f<A, B>(a: A, b: B): A & B; function f<A, B, C>(a: A, ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Issue: The module '@nx/nx-linux-x64-gnu' is not found and cannot be located

I'm encountering issues when trying to run the build of my Angular project with NX in GitHub Actions CI. The process fails and displays errors like: npm ERR! code 1 npm ERR! path /runner/_work/myapp/node_modules/nx npm ERR! command failed npm ERR! c ...

Deactivate the react/jsx-no-bind warning about not using arrow functions in JSX props

When working with TypeScript in *.tsx files, I keep encountering the following error message: warning JSX props should not use arrow functions react/jsx-no-bind What can I do to resolve this issue? I attempted to add configurations in tslint.json js ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

Angular 4: Issue with sending POST data via HTTP requests

I am currently working on developing a Web Application and I am facing an issue with testing the HTTP functions. Here is an example of my code snippet: import { Injectable } from '@angular/core'; import { Headers, RequestOptions, Http } from & ...

I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized ...

Resolving Circular Dependency Error in Angular Component due to Service Integration Testing

Delving into Angular Unit Testing has been a recent focus of mine as I've begun incorporating mock tests in one of my projects. However, I've hit a roadblock with an error popping up in one of my component tests: Error: NG0200: Circular dependen ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...

What is the method to modify the starting point of the animation for the material component "mat-progress-bar" so it initiates from 0 instead of 100

I recently integrated a material progress bar into my Angular project. Here is the code snippet: <mat-progress-bar mode="determinate" value="40"></mat-progress-bar> However, I encountered an issue where upon page refresh, ...