Ways to showcase the refined object array upon clicking a button in Angular

I have been working on a project to create a task management system. The project consists of two main components: itemList and item. The itemList component takes input values for tasks and displays them in the item component.

https://i.sstatic.net/SaRNMm.png

https://i.sstatic.net/RieTHm.png

The itemList component contains an array of objects with checkboxes. My goal is to implement a button filter on this list based on the checkbox selection. When the "Display checked" button is clicked, only the items that are checked should be displayed in the list.

Here is the link to the StackBlitz code snippet: View code here

Below are snippets of the code I have tried:

item-component.html

<div class="listContainer">
<div
  class="checkContainer"
  [style.backgroundColor]="IsChecked ? 'grey' : '#ff6165'"
>
  <div>
    <mat-checkbox
      color="secondary"
      [(ngModel)]="IsChecked"
      (change)="onChange($event, value.task)"
    ></mat-checkbox>
  </div>

</div>
...

item-list.component.ts

 public arrayChecked: TaskType[] = [];

 addCheckedTask($event: any, data: any): void {
    this.arrayChecked.push($event);
    console.log('the task is added', this.arrayChecked);
 }

 displaylist(){
    const selectList$ = this.arrayChecked.map((checked, index) => checked ? 
    this.arrayChecked[index] : null).filter(value => value !== null);
    console.log("DisplayChecked",selectList$);
 }

 removeCheckedTask($event:any, data:any){
    const index = this.arrayChecked.findIndex(list => list.task);
    this.arrayChecked.splice(index, 1);
    console.log(this.arrayChecked);
 }
...

If you would like further assistance with displaying only the checked items in the list when the button is clicked, please refer to the provided StackBlitz link. Thank you!

Answer №1

To ensure that your list is updated based on the checked items, you should use selectList$ instead of filteredData$ in the template.

In your item-list.component.ts file:

displaylist(){
     const selectList$ = this.arrayChecked.map((checked, index) => checked ? this.arrayChecked[index] : null)
    .filter(value => value !== null);
    console.log("DisplayChecked",selectList$);

    // include this code
    if (selectList$) {
      this.filteredData$ = new Observable((subscriber) => {
        subscriber.next(selectList$ as TaskType[])
      });
    }
}

Check out the Stackblitz Demo for reference.

In addition to this, I have added a 'Reset' button within the To Do section of the Demo. This allows you to test undoing the display of checked items. To enable this functionality, I created a reusable function called initlist(), which is invoked in the ngOnInit() method and linked to the 'Reset' button's click event.

For further details, refer to the item-list.component.ts code snippet provided below:

export class ItemListComponent implements OnInit {

  ...
  ...
  ...


  ngOnInit(): void {
    this.initlist();
  }

  ...
  ...

  initlist() {
    if (this.initialData$) {
      this.filteredData$ = combineLatest([
        this._homeService.searchData$,
        this.initialData$,
      ]).pipe(
        map(([searchValue, dailyList]) =>
          this._filterData(searchValue, dailyList)
        )
      );
    }
  }
}

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

Setting up and launching a fresh JS project

Hey there, I recently began a course on Udemy to dive into the world of JavaScript and React. However, after installing Node.js and NPM, I encountered an issue when trying to use npm start. The error message reads "ENOENT: no such file or directory." I&apo ...

When attempting to retry in Next.js, the props obtained from getServerSideProps may

Currently, I am facing an issue with sending axios requests in getServerSideProps and passing the value through props via SSR to the client. The challenge lies in including a token in the header using an instance. In case the token expires, I utilize refre ...

Are your custom guards failing to function properly now?

Previously, the code below was functioning properly until typescript 2.0: class Aluno{ escola: string; constructor(public nome: string){ this.escola = ""; } } class Pessoa{ morada: string; constructor(public nome: string){ this.morada = ...

What is the best way to find out which tab is currently active?

Struggling with Bootstrap 5, I found it challenging to retrieve the activated tab. Even after consulting their documentation, I only managed to obtain the ID of the first button and nothing more. var tabEl = document.querySelector('button[data-bs-t ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Creating a dynamic view that incorporates all the necessary data through the use of Jade, Express, and

In my mongodb setup, I have two collections - notes, which contains individual notes, and notebook, which holds titles along with an array of notes that are referenced by their ids from the notes collection. //example data in notes: { "_id" : ...

Navigating through an array of latitude and longitude pairs during an AJAX request

Just starting out with PHP/AJAX and I could use some guidance. Currently, I have a leaflet map where I'm attempting to link two AJAX calls together. The initial AJAX call retrieves data based on a selected country ISO code. Subsequently, I've ut ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

JavaScript generated form fails to submit

I am currently facing an issue with submitting form data to a PHP file when it is generated using JavaScript. I am unsure of how to resolve this problem. The form submission works fine on a test .html file by itself, but not when it is generated by JavaScr ...

Executing a callback function when a window confirmation is triggered during the onbeforeunload event

Currently, I need to implement a feature where a confirmation window pops up when the user tries to close the page. The code snippet for this functionality is included below: window.onbeforeunload=function(){ if(...) { return "Are you sure you want to ...

What is the best way to eliminate leading zeros in PHP when echoing SQL statements?

Being a front-end programmer on a team of three, my PHP/MySQL skills are fairly basic. However, our back-end programmer is going on vacation and we have a deadline to address a minor visual detail. Currently, we are working on a page that displays multiple ...

What is the best way to manage the delay that occurs when using the append() function?

I'm using jQuery to append an array to a div and I want to display a loading indicator while this process is happening. I added a callback function to my append logic, which works fine. However, the loader disappears before the array is fully rendered ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

Creating functionality in Ionic to allow for the dynamic addition of buttons to the navigation bar

I have a navigation bar and I would like to include a save button on it for just one screen. After going through various blogs, I found that the general advice is to declare buttons in the view rather than accessing them in a controller. But still, isn&apo ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

ngx-infinite-scroll event fails to trigger upon scrolling to the end

I am currently facing an issue while trying to implement infinite scroll using ngx-infinite-scroll in an Angular 4 application. Despite following the documentation and configuring the height of the element while setting scrollWindow to false, the trigger i ...

Fade out the notification div using jQuery in MVC4

I'm a beginner in the world of JavaScript and JQuery and I could really use some assistance with resolving a simple issue that I've encountered. As part of my application's functionality, I am dynamically loading the following div based on ...

What happens when Angular elements don't have an injector?

Exploring Angular's custom elements while steering clear of dependency injection is my current experiment. const MyElementElement = createCustomElement(MyElementComponent, { injector }); customElements.define('my-element', MyElementElement) ...

Tabulating with jQuery Arrays

I am facing an issue when trying to perform calculations with certain numbers. Here is the specific code snippet causing trouble: for (var key in week_total) { $("." + key).html(week_total[key]); } After running this code, I keep getting a value of N ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...