Is it permissible to include $event as an argument in a function that is invoked by ngStyle?

Here is the HTML code I'm having trouble with:

<div *ngFor="let dates of the_list">
    <p  [ngStyle]="{'background-color': changeColor($event)}" [ngClass]="{ 'text-white':(the_list.indexOf(dates))>4 }">{{dates}}</p>
</div>

The corresponding TypeScript function is:

changeColor(event: any){
    this.temp=(<HTMLInputElement>event.target).value;
    if(this.the_list.indexOf(this.temp)===5)
    {
      return 'blue'
    }
    else
    {
      return ''
    }
  }

An error message pops up saying: ERROR TypeError: Cannot read property 'target' of undefined.

I wonder, is it not allowed to pass $event as a parameter in this case?

Answer №1

Here is an example of using let i = index:

<div *ngFor="let dates of the_list; let i = index">
  <p [ngStyle]="{'background-color': i == 5 ? 'blue' : ''}" [ngClass]="{ 'text-white': i > 4 }">
{{dates}}</p>
</div>

Avoid incorporating functions in your HTML code as Angular will execute function() each time change detection occurs to determine if there has been any difference between the previous and current results.

Answer №2

To dynamically determine the styling during each iteration, you can call a method with the index parameter. The code snippet below demonstrates how this can be implemented. It is important to note that $event cannot be utilized in this scenario as it is typically associated with event triggers like click, hover, or key up.

Give this a try:

In your template file

<div *ngFor="let dates of the_list; let i = index">
    <p  [ngStyle]="{'background-color': changeColor(i)}" [ngClass]="{ 'text-white': (the_list.indexOf(dates) > 4) }">{{dates}}</p>
</div>

In your ts file

changeColor(index: number){  
    if(index === 5)
    {
      return 'blue';
    }
    else
    {
      return '';
    }
  }

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

Achieving successful integration of SignalR with Angular 5 within the environment of dot net framework version 4.6.1

Currently, I am in the process of setting up SignalR using the Dot Net Core Angular template found in Visual Studio Professional. Due to having a significant amount of legacy code to maintain, I have opted for .NET Framework 4.6.1. https://i.sstatic.net/j ...

Can you outline the process for troubleshooting the issue of not being able to set breakpoints on a Chrome launch configuration when working with Angular

Using Angular 13 / Chrome 111 / VSCode 1.76.1 / Node 16.19.1 I am encountering a strange issue where I am unable to set breakpoints in VSCode after my code has live-reloaded. Yesterday, the configuration in my launch.json was working fine: "configur ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

Tips for configuring VSCode to display strictNullChecks Typescript errors

Whenever I compile my project using the specified tsconfig.json settings, an error occurs after enabling strictNullChecks: true. { "version": "2.3.4", "compilerOptions": { "allowSyntheticDefaultImports": false, "removeComments": tr ...

Why is interpolation not allowed in Angular 2 for binding to my child component?

If I plan on assigning the 'src' attribute of an 'image' tag, I have the option to use either <img src='{{heroImageUrl}}'> or <img [src]='heroImageUrl'> However, when dealing with a child component us ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

Angular: Dynamically add or delete an interceptor based on conditions

Is it possible to dynamically include or exclude an interceptor based on user selection? For my application, I want to enable Azure AD based SSO using the @azure/msal-angular package https://www.npmjs.com/package/@azure/msal-angular that provides an inter ...

Vue cannot detect the component that is provided by my plugin

This unique plugin, currently only includes a single component (coded in TypeScript): import _Vue, { PluginObject } from "Vue"; import MyComponent from "./MyComponent.vue"; const VuePlugin: PluginObject<void> = { install(Vue: typeof _Vue): void { ...

Explore an asynchronous PipeTransform experiment

Situation I have created a simple PipeTransform with an asynchronous twist. Why? Well, I have developed my own i18n service to handle parsing, pluralization, and other complexities, which returns a Promise<string>: @Pipe({ name: "i18n", pur ...

Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone ex ...

Issues with accessing view variables within a directive query are persisting

I am struggling with a specific directive: @Directive({ selector: '[myDirective]' }) export class MyDirective implements AfterViewInit { @ViewChild('wrapper') wrapper; @ViewChild('list') list; ngAfterViewInit() { ...

The flow union type operates smoothly without any errors occurring

In the code snippet below, I have defined a type 'Something' which can have three possible values: 'A', 'B', or 'C'. The function 'f' takes an object of type Something as input and returns a string based on ...

Angular fails to eliminate the colon (:) preceding the route

Currently, I am working on my own version of the Angular 4 Hero tutorial where I am creating a student list application. The goal is to display a list of students and show detailed information when a particular student is clicked. I have reached the point ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Remove the hyphen from a user input field using Angular 2 and reactive forms

After deleting data from input fields, I am facing an issue where the dynamic addition of a hyphen prevents the input field from being cleared. Is there a solution to this problem? How can I delete or clear the input fields effectively? Although I have ad ...

Tips for setting up Typescript to deduce discriminated unions when `is` and `never` are included in the code

In the past, I had a library included in my project that I later removed (deleted from package.json). However, this library had a peer dependency on fp-ts, so I had to directly add fp-ts to my project. The fp-ts library includes an Either type which allows ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

Expanding the number of buttons for <ul> in creating a responsive navigation system using Angular

My navigation consists of 8 items (li), and as the resolution shrinks, the items are pushed onto a new line. I am looking to implement a feature where if an item doesn't fit in the navigation anymore, a "MORE" dropdown button appears on the right side ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...

What is the best way to filter an array based on the value entered in an input field?

Hello World! I am diving into the world of Javascript and need some assistance. I want to utilize the value entered into an input field to filter out specific elements from an array named "e". Despite my best efforts, I can't seem to pinpoint what&apo ...