Retrieving the latest status array by index using Typescript in Angular

Need help with this code logic. I am working on an array and function :

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name: any = 'World';

  myArray: any = 
  [
    {
      id: 2001,
      name:"a"
    }, 
    {
      id: 2002,
      name:""
    }, 
    {
      id: 2003,
      name:"b"
    }, 
    {
      id: 2004,
      name:"c"
    }, 
  ];
 
  ngOnInit() {
   this.removeEmptyContent();
  }

  selectFile(event) {
    console.log('event', event);
     
    this.myArray.forEach( (myObject) => {
        console.log('myObject', myObject); 
            if(myObject.length > -1){
                console.log('completed'); 
            } else {
                console.log('in progress'); 
        }
    });   
    console.log('getlast', this.myArray.length > -1);
  }

  removeEmptyContent() {
    this.myArray.forEach( (myObject, index) => {
      if(!myObject.name){
          this.myArray.splice(index, 1);
      }
    });   
  }
}
<hello name="{{ name }}"></hello>
<ul>
  <li *ngFor="let item of myArray">
    <div (click)=selectFile(item)>
      {{item.name}}
    </div>
  </li>
</ul>

I need to change the value in the array when selecting the last item. When I select indexes 0, 1,.. the status should be "progress", but when I select the last index I want the status to be "complete". How can I achieve that?

Note: The code above requires fixing and updating

Thanks in advance

Answer №1

One possible approach is to implement logic similar to the following. It may not be the most elegant solution, but it should get the job done. Begin by creating an array for your selected items:

Check if the item that was selected is already in the list of selected items.

  • If the item is already selected, do nothing.
  • If the item is not already selected, add it to the list.
  • If the number of items in the selected item list equals the number of items in myArray, then the

Below is a sample code snippet:

ngOnInit() {
   this.cleanupItems();
   this.selectedItem = []
}

selectItem(event) {
    console.log('event', event);

    if(this.selectedItem.find(item => item.id === event.id)){
        this.selectedItem.push(event)
    }
    if(this.selectedItem.length === this.myArray.length){
        console.log('All items selected'); 
    } else {
        console.log('Selection in progress');
    }
}

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

Circular referencing in Angular models causes interdependence and can lead to dependency

I'm facing a dependency issue with the models relation in my Angular project. It seems to be an architecture problem, but I'm not sure. I have a User model that contains Books, and a Book model that contains Users. When I run this code, I encoun ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

Despite the error message stating that it cannot find module 'angular2/core', the application is still functioning properly

Imagine you have an Angular2 application with a file named app.component.ts that contains some import statements: import {Component} from 'angular2/core'; import {FiltersService} from "./services/filters-service"; import {SearchPipe} from "./ ...

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

Encountering an issue with Java code

Whenever I attempt to add an order (which was previously created using the Order class) to the waitingList, I encounter the following error: java.lang.NullPointerException at DeliveryLog.addOrder(DeliveryLog.java:41) I am currently using BlueJ for wr ...

Evaluation of button display based on certain conditions

I currently have two different render functions that display certain elements based on specific conditions. The first render function looks like this: private render(): JSX.Element { return ( <div> {this.props.x && this.state.y ...

Encountering a "args" property undefined error when compiling a .ts file in Visual Studio Code IDE

I've created a tsconfig.json file with the following content: { "compilerOptions": { "target": "es5" } } In my HelloWorld.ts file, I have the following code: function SayHello() { let x = "Hello World!"; alert(x); } However ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

What could be the reason for React not memoizing this callback?

I am encountering an issue with my Next.js project where the _app.tsx file contains the following code: const Root = ({ Component, pageProps }) => { ... const handleHistoryChange = useCallback((url) => { console.log({ url }); }, []); u ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Property does not exist when dispatching in React Redux within componentDidMount

Currently, I am navigating my way through my initial project using React + Redux and have hit a few roadblocks while attempting to dispatch a function in the componentDidMount section. I tried to emulate the Reddit API example project from the Redux docume ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

Having difficulty utilizing defineProps in TypeScript

For some time now, I've been utilizing withDefaults and defineProps. Unfortunately, this setup has recently started failing, leaving me puzzled as to why! Here's a simple SFC example: <script setup lang = "ts"> const props ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

Error encountered while uploading a file with Fastify and Nestjs

I encountered an issue while attempting to upload a file to my nest.js server, receiving the following error message: Error: Unsupported Media Type: multipart/form-data; boundary=--------------------------140603536005099484714904 My approach was based ...

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Unspecified parameter for Next.js dynamic route

Currently, I am developing an e-commerce application using next.js with Typescript and MongoDB. To better understand my project, let's take a look at my existing file structure: https://i.stack.imgur.com/tZqVm.png The mainPage.tsx file is responsibl ...