Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation.

To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below:

import {Directive, Input, OnChanges, SimpleChange, SimpleChanges} from "@angular/core";
import {NgForOf} from "@angular/common";

@Directive({
    selector: "[ngFor][ngForIn]"
})
export class NgforinDirective<T> extends NgForOf<T> implements OnChanges {

    @Input() public ngForIn: any;

    public ngOnChanges(changes: SimpleChanges): void {
        if (changes.ngForIn) {

            if (this.ngForIn) {
                this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
                const change = changes.ngForIn;
                const currentValue = Object.keys(change.currentValue);
                const previousValue = change.previousValue ? Object.keys(change.previousValue) : undefined;
                changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
            }
            super.ngOnChanges(changes);
        }
    }
}

The current challenge is accessing the value of object[key] multiple times in the template. Currently, I am handling it using the following method (although not ideal):

<div *ngFor="let key in object">
     {{object[key]}}

However, my goal is to be able to achieve something like this:

<div *ngFor="let key in object; let value = object[key]">
     {{value}}

In my exploration, I have delved into the source code for ngForOf, where I observed the inclusion of local variables such as "index" and "odd".

I believe creating a local variable within the custom directive that can provide the value of the object[key] during iteration might offer a solution. However, I am uncertain about how to proceed with this approach or if there exists a simpler alternative that has eluded me.

Have you encountered a similar challenge and discovered a resolution?

Thank you!

Answer №1

If you're looking to achieve a similar result, you can utilize the *ngFor directive in Angular. Obtain the keys of your object by using Object.keys(yourObject), then proceed to iterate through them and display the corresponding values.

import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let key of keys;">
        {{ key }}: {{ person[key] }}
      </li>
    </ul>
  `,
})
export class App {
  keys: string[];
  person: object;

  constructor() {
    this.person = {
      'First Name': 'Bob',
      'Last Name': 'Smith',
      'Age': 44,
    };
    this.keys = Object.keys(this.person);
  }
}

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App],
})
export class AppModule {}

Plunkr: https://plnkr.co/edit/BOgMT8XYphirNi6kObZv

If preferred, you also have the option to create a Pipe that retrieves the object keys instead of handling it within your component. The use of object[value] should not pose any significant issues.

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

Discover how to use jQuery to add CSS styles to every span element on a

I'm currently using JavaScript and jQuery to create a tree structure in ASP.NET MVC. There's an 'add' button that will add siblings and child nodes at the same level. To determine the appropriate action, I have implemented the followi ...

Using a React component to import a module for publishing on NPM

Creating my first React component for NPM publication has been quite the learning experience. I decided to use the react-webpack-component package from Yeoman to kickstart my project. However, upon installing and importing my component into a React app, I ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

The div smoothly descended from the top of the page to the center under the control of jQuery

I am trying to implement a feature where a div slides down from the top of the page to the center when a button is clicked. However, my current code seems to be causing the div to slide from the bottom instead of the top. Ideally, I want the div to slide ...

Retrieve the Query String Information from a Link and Generate a New Link in Another List

I am looking to extract information from a link in #list and then use that information to create a new link in #list3. The link I have is http://jsfiddle.net/4y5V6/24/. Is there a way to set it up so that when a link is clicked, it automatically gets added ...

What causes my backend to crash when incorrect credentials are entered?

Whenever I input incorrect credentials on my login page, it causes the backend to crash. I want to avoid this situation and prevent my backend from crashing. Can somebody please assist me in identifying and rectifying the mistake? I am using MongoDb as my ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

Display a div when hovering over an image using jQuery

I've spent a good 30 minutes searching on Stack Overflow for a solution, but I haven't been able to find it yet. It's possible that I'm not sure what exactly to look for. Essentially, I have a div that contains an image and some text. ...

The attempt to run 'setProperty' on 'CSSStyleDeclaration' was unsuccessful as these styles are precalculated, rendering the 'opacity' property unchangeable

I am attempting to change the value of a property in my pseudo element CSS class using a JavaScript file. Unfortunately, I keep encountering the error mentioned in the title. Is there any other method that can be used to achieve this? CSS Code: .list { ...

Expanding using CSS3 to ensure it doesn't take up previous space

Currently, I am working on an animation for my web application. More specifically, I am looking to scale certain elements using CSS3 with the scaleY(0.5) property. These elements are arranged in a vertical list, and I want to ensure that they do not take u ...

Transferring a JSON file between components within Angular 6 utilizing a service

I have been facing an issue in passing the response obtained from http.get() in the displayresults component to the articleinfo component. Initially, I used queryParams for this purpose but realized that I need to pass more complex data from my JSON which ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

angular pipe and tap methods fail to execute the designated function

I am encountering a problem when calling a function in my login service. I have tried using a pipe and tap. Interestingly, when I use res => console.log(res), it outputs the desired result. However, when I attempt to call a function, it seems that the ...

Creating a custom directive for input validation in Angular

I am currently working on building a basic custom directive in AngularJS to validate if the user input is an integer or not. When the user types in an integer, I want an error message to display at the bottom that states "integers are not allowed". Do yo ...

Cannot execute loop

I'm currently working on creating a loop within my component that involves making server calls: getBeds() { this.patientService.getBeds(this.selectedWard).subscribe( result => { console.log(result); this.beds = result; this.getBedDet ...

How can you start a jQuery script following a triumphant Ajax callback?

Having some trouble getting jQuery to execute after a successful Ajax response. Even though I have it in the success callback, it doesn't seem to be working as expected. I came across a potential solution here, but I'm having difficulty understan ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Ways to use string functions in JavaScript to substitute with /

Here is the image path I am working with: var str = "D:\Poc\testProject\DataPush\public\unzip\cust\AccountData\2.jpg" When I included "unzip" in the path, it threw an error as shown in this image, but when ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

New to NodeJS: Utilizing Requestify to Retrieve Data from Another URL

As a newcomer in the world of NodeJs, I am faced with the task of transitioning my CodeIgniter server APIs to Node.js. Currently, I am utilizing requestify to retrieve data from a web service, and once this is accomplished, I intend to invoke an insert met ...