What is the best way to add a global variable to every item within an ngFor loop in Angular 4?

My challenge is to access a global variable public right: any = 30;

I need to uniquely call this variable from each element and increment it by 30 in an ngFor loop iterating over the People object:

interface Person {
  name: String,
    title: String,
    content: String,
    image: String,
    rate: String,
    classActive: String,
    active: Boolean
}

@Component({
  selector: 'app-testimonials',
  templateUrl: './testimonials.component.html',
  styleUrls: ['./testimonials.component.scss']
})
export class TestimonialsComponent {
  people: Person[] = [{
      name: 'Douglas  Pace',
      title: 'Parcelivery Nailed The Efficiency',
      content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' +
        'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy',
      image: '../../assets/img/profile_pics/profile_pic.jpg',
      rate: '4.5',
      classActive: 'testimonials__selected-visible',
      active: true
    },
    {
      name: 'Naseebullah  Ahmadi',
      title: 'Parcelivery Nailed The Efficiency',
      content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' +
        'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy',
      image: '../../assets/img/profile_pics/profile_pic.jpg',
      rate: '4.5',
      classActive: '',
      active: false
    },
    {
      name: 'Haseebullah Ahmadi',
      title: 'Parcelivery Nailed The Efficiency',
      content: 'Since I installed this app, its always help me book every tickets I need like flight, concert, ' +
        'movie or hotel. I don\'t need to install different app for different ticket. The payment is also very easy',
      image: '../../assets/img/profile_pics/profile_pic.jpg',
      rate: '4.5',
      classActive: '',
      active: false
    }
  ];
  public right: any = 30;

  constructor() {}
  stackItem(a) {
    console.log(a);
  }

}

<div *ngFor="let person of people; let last = last" 
     class="testimonials__card-container"
     #__person
     [ngClass]="{'testimonials__card-container--not-visible': !person.active}" 
     [style.right]="stackItem(__person.right)">
</div>

In Angular 2, we used to call global variables as an instance for each element in ngFor, but that changed in angular 4. Are there any alternative approaches?

Answer №1

  <div *ngFor="let individual of individuals; let last = last" 
       class="feedbacks__testimonial-box"
       #__character
       [ngClass]="{'feedbacks__testimonial-box--hidden': !individual.active}" 
       [style.right]="stackElement()">
  </div>
       ---------------- 
  stackElement() {
       this.right = this.right + 30;
       return this.right;
  }

Answer №2

I found success with the following code snippet:

<div *ngFor="let individual of people; let last = last" 
     class="testimonial__card-wrapper"
     #individualRef
     [ngClass]="{'testimonial__card-wrapper--hidden': !individual.active}" 
     [style.right]="adjustRightLocation(right)">
</div>

It's important to note that right is a property of the component class, not of the person object, hence we are referencing it as such and not as individual.right.

If you want the uniqueness of the right property for each person, consider adding it directly to the people objects.

Additionally, the hash symbol (#) allows us to define a template reference variable for the attached element. In this case, we have created a unique template reference variable named individualRef for each div element, corresponding to the divs themselves rather than the associated person objects.

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

The process of file transformation using es6-transform-karma-typescript can sometimes result in karma encountering an obstacle

I'm currently in the process of setting up a unit testing framework using typescript, karma, and mocha. I am utilizing karma-typescript for transpiling and es6-transform-karma-typescript to convert es6 code to browser-compatible es5 code. However, my ...

Retrieve the text content from the HTML document

I'm facing a beginner's challenge. I have a div element and I want to extract the URL from the data-element attribute into a .json file Is there a way to do this? <div content="" id="preview" data-element="http://thereislink" class="sample ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

What is the best approach for organizing type declaration files when using Vite in a React TypeScript application?

Currently in the process of transitioning my application from Webpack to Vite. Seeking guidance on the optimal method for including the following: /// <reference types="vite/client" /> There is an existing file types/global.d.ts, and I&ap ...

Exporting a Middleware member is essential for defining Koa middleware type definitions

Currently utilizing KoA with Typescript and incorporating the KoA middleware KoA-static and KoA-bodyparser. Ensuring that I have installed the type definition packages @types/koa, @types/koa-bodyparser, and @types/koa-static. However, upon running tsc, enc ...

Currently honing my skills in Angular 2, but encountering an error stating "Bindings cannot contain assignments."

<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" [male]= "gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (on ...

Invoke a TypeScript function within JavaScript code

As a result of the limitations of IE10 and earlier versions, I find myself in need to reimplement the Import/Upload functionality that I had initially created since FileReader is not supported. After some consideration, I have opted to utilize an iFrame in ...

Navigating through object keys in Angular 5 by iterating through them

I have an object with protected products: protected products: { [key: string]: { color: string, brand: string, }; } = {}; products = { scan12345: {color: "Orange", brand: "X"}, scan13813: {color: "Pink", brand: "X"}, } How can I loop through t ...

ng2-file-upload is incorrectly defining the Content-Type

I used the tutorial provided at Everything was working correctly with Postman, but when I attempted to use it in my application, it wasn't successful. While I can see files being returned from the API in Postman, they appear as undefined in my app. ...

Is it possible to confirm that a value is a valid key without prior knowledge of the object's keys during compile-time?

Is there a way in TypeScript to declare that a variable is a keyof some Record without prior knowledge of the keys? For instance, consider an API response returning JSON data. Is it possible to define a type for the keys of this payload to ensure that whe ...

Incorporating New Relic into an Angular Universal application running on Node.js

I am in the process of integrating newrelic into my node.js application, which is built with angular universal and bundled using webpack. The first line in main.server.aot.ts reads: const newrelic = require('newrelic'); In addition, I have inc ...

Navigating an object in TypeScript: the right approach

Curious if there might be a bug in TypeScript? Just seeking clarification on whether my code is incorrect or if there is an actual issue with the language. interface Something { key1: string; key2: number; key3: boolean; } const someObject: S ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Passing server parameters to ngModule after the version upgrade to RC5

I'm facing a new challenge in passing parameters to my application. With the transition to RC5, it seems like I now have to use ngModule for this purpose. The previous method mentioned in this solution (Passing asp.net server parameters to Angular 2 a ...

Can a TypeScript interface be exported as the result of a function?

Looking for a way to convert JSON schema to a Typescript interface in a more efficient manner. Here is an example of what the current method looks like: //Input var scriptSchema = { type: 'object', properties: { src: { type: &apo ...

Struggling to configure Sass with @snowpack/app-template-react-typescript

I'm struggling to integrate Sass with the @snowpack/app-template-react-typescript template. I attempted to follow the steps outlined in this guide, but so far I haven't been successful. I even created a new project and tried adding it, but not ...

What is the method to assert that two arguments are equal within a function?

When working with TypeScript, you can pass a value to a function and have that function assert the value is true for type narrowing. For example: function assertTrue(v: unknown, message: string): asserts v { if (!v) { throw new MySpecialError(message ...

Transform commitment into observable Keycloak

I'm struggling with the keycloak methods and find it overwhelming to redo them. I also have some confusion on how it works. export class AuthGuard extends KeycloakAuthGuard { constructor( protected readonly router: Router, protected readonly ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...