What is the best way to implement line-through text decoration for a list item when it is clicked in an Angular application? Additionally, how can the "completed" value in

<h1>My Exciting To Do List</h1>
<input #newTask>
<button (click)="addTask(newTask.value)">Add Task</button>

<ul>
  <li *ngFor="let task of tasks">{{task.name}}</li>
</ul>
export class MyToDoAppComponent implements OnInit {
  title = 'awesome-todo-app';
  tasks:any;
  

  constructor(private taskService:TaskService) {}

  ngOnInit() {
    this.taskService.getTasks()
    .subscribe(response => {
      this.tasks = response;
      console.log(this.tasks)
    })
  }

  
  
  addTask(name: string){
    
    this.tasks.push({
      taskId: 1, 
      name, completed: false
      
      
    });
    console.log(this.tasks)
  }

This is the progress I've made so far and any assistance would be greatly appreciated :)

I've searched extensively on various platforms for a solution, but unfortunately haven't found one that works.

Answer №1

To implement conditional styling, consider utilizing the ngClass directive in Angular and set it based on a true/false condition.

Answer №2

Check out the StackBlitz demo here!

<h1>Manage Your Tasks</h1>
<input #newTask>
<button (click)="addTask(newTask.value)">Add Task</button>

<ul>
  <li *ngFor="let task of tasks">{{task.title}}</li>
</ul>

import { Component, OnInit } from '@angular/core';
import { of } from 'rxjs';

@Component({
  selector: 'my-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.css'],
})
export class TasksComponent implements OnInit {
  title = 'task-manager';
  tasks: { title: string; userId: number; completed: boolean }[];

  ngOnInit() {
    of([{ title: 'example', userId: 0, completed: false }]).subscribe(
      (response) => {
        this.tasks = response;
        console.log(this.tasks);
      }
    );
  }

  addTask(title: string) {
    this.tasks.push({
      userId: 1,
      title,
      completed: false,
    });
    console.log(this.tasks);
  }

  markAsDone(task: { title: string; userId: number; completed: boolean }) {
    task.completed = true;
  }
}
p {
  font-family: Roboto;
}

.strikethrough {
  text-decoration: line-through;
}

Answer №3

  1. Include a new property in each todo object named isDone, or something similar.
  2. Create a function named toDoClicked() or equivalent, and add
    (click)="toDoClicked(todo)"
    to your li element
  3. Apply a conditional class
    [ngClass]="{'strikethrough-styling': toDo.isDone}
    also to the line

After completing these steps, your HTML line should resemble this:

<li *ngFor="let todo of todos" (click)="toDoClicked(todo)" [ngClass]="{'strikethrough-styling': toDo.isDone}>{{todo.title}}</li>

You must define a CSS class called strikethrough-styling, and you may need to utilize an <a> tag instead of li, as I am unsure if li supports (click) binding.

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

What is the difference between adding the .js extension when importing files in TypeScript versus Angular imports?

When working on my TypeScript project, I've encountered an issue where I need to include the *.js extension when importing files. If I omit the extension, the project will build successfully but fail at runtime in the browser due to file not found err ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Step-by-step guide to linking a matTooltip with a disabled mat-tab

Is there a way to attach a matTooltip to a mat-icon in a disabled mat-tab? It seems that this feature is disabled when the mat-tab itself is disabled. Has anyone else encountered this issue? (I am unable to place the mat-tab within a div, of course) Than ...

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

Expanding a JSON data structure into a list of items

In my Angular service script, I am fetching customer data from a MongoDB database using Django: getConsumersMongodb(): Observable<any> { return this.httpClient.get(`${this.baseMongodbApiUrl}`); } The returned dictionary looks like this: { &q ...

Struggling to set up @angular/material in Angular version 17

When I run ng add @angular/material in my project, it fails and shows the following error message: The package @angular/angular_material will be installed and executed. Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resol ...

The ngx-mat-intl-tel-input plugin is experiencing issues with functionality within the Angular 17 framework

I am currently using Angular 17 and here are the specific Versions/Details: Angular CLI: 17.3.8 Node: 18.20.2 Package Manager: npm 10.5.0 OS: linux x64 Angular: 17.3.12 My goal is to import the ngx-intl-tel-input library in order to validate phone numbers ...

Angular TSLint: Proceed to the following stage despite any encountered errors

I'm facing issues with TSLint in my Azure Devops Build Pipeline. Despite encountering lint errors, I need the build pipeline to proceed to the next step. How can I achieve this? Command Line: - script: | npm run lint > tsLintReport.txt ...

Is it beneficial to consolidate masterdata calls into a single call?

Our application is built using REST with an Angular 2 client. We frequently make calls to master data APIs such as country and agreement during login, totaling around 6-7 calls. From a performance standpoint, would it be beneficial to consolidate these c ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

A special function designed to accept and return a specific type as its parameter and return value

I am attempting to develop a function that encapsulates a function with either the type GetStaticProps or GetServerSideProps, and returns a function of the same type wrapping the input function. The goal is for the wrapper to have knowledge of what it is ...

Revolutionizing Angular 8 with Hot Module Replacement

I have just embarked on a new Angular project and my goal is to incorporate HMR (Hot Module Replacement). Despite meticulously following the steps outlined in this guide, I continue to encounter the following errors: Utilizing the most recent version o ...

Having trouble dispatching a TypeScript action in a class-based component

I recently switched to using this boilerplate for my react project with TypeScript. I'm facing difficulty in configuring the correct type of actions as it was easier when I was working with JavaScript. Now, being new to TypeScript, I am struggling to ...

unable to initiate a new project in angular version 8

Upon attempting to add a new project in Node.js command prompt, I encountered an error message stating: "The system cannot find the path specified." This has left me perplexed about how to proceed with creating a new project. Your environment is configure ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

I encountered a roadblock with my Npm start process when it got stuck at 70% completion after incorporating the "lazy

I have encountered a problem that has previously been discussed here, but none of the solutions seem to work for me. I recently incorporated this module into an existing project: import { NgModule } from '@angular/core'; import { CommonModule } ...

Using Angular and TypeScript/javascript singletons across multiple browser tabs

I am curious about whether the TypeScript singleton class, used as an MVC model object in my Angular application within one browser tab, would be different from or the same as the singleton loaded into another tab within the same browser instance. The set ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

Error in Typescript: Uncaught ReferenceError - "exports" is undefined

Encountering an error message (Uncaught ReferenceError: exports is not defined) when attempting to import other TypeScript files in the main app.ts app.ts import { LanguagesConfigs } from './LanguagesConfigs'; let languagesConfigs = new Languag ...

There is no way to convert a strongly typed object into an observable object using MobX

I have been utilizing the MobX library in conjunction with ReactJS, and it has integrated quite smoothly. Currently, I am working with an observable array structured as follows: @observable items = []; When I add an object in the following manner, everyt ...