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

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

javascript issue with setting the id attribute on a select option

I can't seem to set the id attribute in my select element using JavaScript. When I inspect it, the id attribute isn't showing up... Here's the first method using JS: var selectorElem = document.getElementById('selector') var ...

Tips for utilizing Provide/Inject in Vue.js while leveraging TypeScript

I am currently working with Vue.js and TypeScript along with the vue-property-decorator package. The documentation suggests that I can achieve something like this: import { Component, Inject, Provide, Vue } from 'vue-property-decorator' const s ...

Encountering an Error When Trying to Run Npm Install in React-Native

I encountered an issue while trying to perform an npm install on my project, so I deleted the node modules folder in order to reinstall it. However, even after running npm install in the appropriate directory, I continued to face numerous errors in my term ...

The issue with the tutorial is regarding the addHero function and determining the source of the new id

Whenever I need to introduce a new superhero character, I will utilize the add(string) function found in heroes/heroes.component.ts add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({ name } as H ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

What could be causing the delay in loading http requests in Angular?

When attempting to update the array value, I am encountering an issue where it works inside the httpClient method but not outside of it. How can this be resolved in Angular 14? Here is a snippet from app.component.ts: ngOnInit(): void { this.httpC ...

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

You cannot use Angular 5 to send a post request with a token that has been retrieved

Hello, I'm facing an issue with making a post request in Angular 5. The token I retrieve seems correct as it works fine when tested with Postman. Can someone provide me with a hint or suggestion on what could be going wrong? AuthService.ts getProfi ...

Looking for guidance on converting JS code to TypeScript? Let's tackle this TS test together!

I am facing the challenge of encapsulating a very complex SDK into a layer of code. I have attempted to utilize union and index types for this task, and below is a demo that I have created. How can I implement the bar method in TypeScript to pass the conso ...

What causes the canLoad function to create an endless loop when rerouting?

Utilizing Angular's canLoad function in my AuthGuard to authenticate a lazy loaded module at the root of my application. If the user is not authenticated, the module will not load and the user will be directed to the login page. This process works sm ...

What is the method to update reference models in mongodb by generating documents within a different model?

In my API, I have three models: Patient, Doctor, and Reviews. The Reviews model is referenced in the Doctor model, with the intention that a patient can post a review for a specific doctor using Review.create(). However, even after the review document is c ...

Step-by-step guide for adding an object to a Material UI select component

I am in the process of incorporating a Select component with reactjs material ui and typescript. Yet, I encounter this typing error: Property 'id' does not exist on type 'string'. Property 'name' does not exist on type ' ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

Creating an Angular form from scratch using HTML

I've developed a component named login. Initially, I created an HTML form called login.component.html and then decided to convert it into an Angular form. To achieve this, I inserted <form #loginform="ngForm"> in the login.component.ht ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

Batch requesting in Typescript with web3 is an efficient way to improve

When attempting to send a batch request of transactions to my contract from web3, I encountered an issue with typing in the .request method. My contract's methods are defined as NonPayableTransactionObject<void> using Typechain, and it seems tha ...