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

Experiencing difficulties posting on route due to receiving an undefined object instead of the expected callback in Node Js

I am working on implementing a feature in my application where users can create a favorite route. When a user adds a campground to their favorites, the ID of the campground is saved in an array within the schema. The process involves checking if the campgr ...

When Jquery JSON DOM fails to load data

I've been trying to implement this functionality on my website by following various tutorials, but I am facing an issue where the data is not displaying anywhere. Initially, it was showing the return value of json_encode, but now it's not even do ...

How to capture a specific part of a model using Autodesk Forge Viewer

I have a situation where I have 20 element Ids that I need to capture screenshots of in a specific size (400x400) like a detail view. The current viewer I am using has different dimensions, so I'm wondering if there is a way to achieve this and return ...

Express.js encounters a 404 error when router is used

I am currently in the process of learning and consider myself a beginner at Node.js. My goal is to create a basic REST API, but I keep encountering an error 404 when attempting to post data to a specific route using Postman to test if the information has b ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

typescript: textual depiction of a generic type T

I have a requirement to develop a method that is capable of handling generic data types, and I need to incorporate the type information into the method Our API requires passing the entity name as a parameter: http://server/api/fetch/Entity/123 It's ...

When retrieving objects using Angular's HttpClient, properties may be null or empty

I am working with a service class in Angular that utilizes the HttpClient to retrieve data from a web service. The web service responds with a JSON object structured like this: { "id": "some type of user id", "name": "The name of the user", "permiss ...

Incorporating an Array into a JSON Object and transmitting it to a server

I have stored an Object in a .json file that contains only an Array. Now I want to prompt the user for a word and add it to this Array. Below are the relevant code snippets: function addWord() { let myWords = getWords(); let newWord = prompt("Ple ...

What causes the discrepancy in calculating marginTop on a desktop browser compared to a mobile browser?

In the top screenshot, you can see a representation of my Pixel 6XL connected to my laptop in USB debug mode. The checkered area represents the URL bar on the Chrome browser displayed on my Pixel device. Below that, the second screenshot shows the view fr ...

Tips for effectively utilizing typescript interface with the OR operator

I'm a beginner when it comes to TypeScript. I have the following code snippet that I am working on: interface InitialData { active: boolean; status: boolean; } interface Item { id: number; name: string; Data: InitialData; } interface Main ...

When running the 'npm install' command, it automatically downloads and installs the most recent versions of the libraries, regardless of the versions specified in the package.json file

When I tried to download the dependencies for my Angular project, I used the npm install command in the command prompt at the project level folder. To my surprise, it seems like this command is installing the latest versions of the libraries instead of the ...

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

Utilizing AngularJS and RequireJS to incorporate a controller into the view

I am facing an issue while trying to add an Angular controller to my HTML view. Typically, in Angular, this can be done using: ng-controller="<controller>". However, due to my use of RequireJS, I have had to implement it differently. I need to includ ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

How about rejuvenating a Div with some PHP magic inside?

My goal is to automatically update a div every x seconds by using the following code: The div only contains a small PHP timezone code. This is the code snippet I am implementing: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ li ...

Encountering an error in Vue.js where a "cannot read property of undefined" message is displayed when attempting to use v

While attempting to use v-model on an array item's property, I encountered the error message "[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined' when loading the page. This resulted in a ...

What strategies should be employed when creating e2e tests that require a specific order of execution?

In the process of developing e2e tests for our angular app using Cypress.io, we are encountering a challenge. While we understand that tests should ideally not rely on each other, it seems challenging to avoid in a practical application. Consider a user ne ...

typescript - specifying the default value for a new class instance

Is there a way to set default values for properties in TypeScript? For example, let's say we have the following class: class Person { name: string age: number constructor(name, age){ this.name = name this.age = age } } We want to ens ...

Handling Movement Events in PrimeNG PickList ComponentsExplore the onMove and onMoveAll event

I am currently utilizing PrimeNG PickList version 5.0.0-rc0 in my Angular 5 project. An issue I am encountering is that the functions onMoveToTarget and onMoveAllToTarget are being triggered simultaneously, which, in my opinion, should not happen. The Pick ...