What is the process for retrieving an element from component interaction?

Is there a way to dynamically change the background color based on component interaction?

I am looking for a method to compare the target element with the current element.

For example, here is a hypothetical scenario:

<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target"  >any text ...</span>
<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" >any text ...</span>
<span 
     [style.background]="targetElem == this ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" >any text ...</span>
enter code here

What is the best way to access elements(this) from within component interaction?

Answer №1

To effectively compare values in a template, it is necessary to assign a value that can be used for comparison later on. The (click) event and the style evaluation occur at different points in the change detection lifecycle, which contributes to the overall functionality.

Template

<span *ngFor="let item of spans"
     [style.background]="targetElem === item ? 'red' : '#eee'"
     (click)="targetElem = item">item.text</span>

Code

spans = [ 
  { text: 'Text 1' },
  { text: 'Text 2' },
  { text: 'Text 3' }
];

targetElem;

Answer №2

One way to declare DOM elements as variables is by using the # syntax:

<span 
     [style.background]="targetElem == s1  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target"  #s1>any text ...</span>
<span 
     [style.background]="targetElem == s2  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" #s2>any text ...</span>
<span 
     [style.background]="targetElem == s3  ? 'red' : '#eee'" 
    (click)="targetElem = $event.target" #s3>any text ...</span>

This code snippet was tested in StackBlitz

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

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...

Unraveling the Intricacies of Manipulating Values through mockStore.overrideSelector

There is a certain selector that I'm working with, and it returns either true or false. To ensure accurate testing in my unit test, I need to cover scenarios where this value is both true and false. To set up for the test, I have initially configured ...

Exploring how to utilize class properties within Angular templates

I am facing an issue with using a template property in Angular. Despite my attempts, it is not functioning as expected and I am unable to pinpoint the cause of the problem. To illustrate, I have set up a demonstration here: https://github.com/Fulkerson/an ...

Does Typescript extend Node.js capabilities?

I am currently developing an application using Typescript and came across some sample Node.js code online. Can I directly use the Node.js code in my Typescript application? Essentially, I am wondering if Typescript is encompassed within Node.js. A simila ...

The term "Movie" is not compatible as a JSX component

Currently working on a movie app project but encountering issues with handling arguments and displaying them properly using TypeScript. The challenge lies in trying to map the movie object, display them individually on the homepage, and showcase all the re ...

The webpage is currently experiencing difficulty in displaying any information

As a beginner in React and typescript, I am working on a simple application that fetches data from an API and displays it on a web page. Despite fixing some errors and seeing the data in the console log, I am struggling to display any data on the actual we ...

Angular 2 - Ensuring mandatory fields are completed when checkbox is checked

Hey everyone, I'm a newcomer to Angular2 and JS frameworks in general. I've been following tutorials on the official site but I can't seem to find a solution to my problem. So, I have a checkbox that is optional, but if it is checked, a new ...

Issue: Missing provider for t specifically when running in production mode

I've been researching and found that missing modules or services could be the cause of this issue, but I have double-checked and everything seems to be in order. Here is the complete error message: vendor.96643eaf6ee79e7b894d.bundle.js:1 ERROR Error ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

What causes the return value type in a functional interface to be loosely implemented in Typescript?

In an attempt to explain a specific partial type of return value for a functional interface, I have encountered an issue. Within my IStore interface, there is only one property called test. When assigning this interface to the function foo, which returns ...

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...

Updating a single record in Angular 9 using Angular Material's Mat table

I am facing a unique scenario and seeking assistance with the following issue. In my application, I utilize a mat table to display data which is constantly being updated through signalR from the backend. This frequent data updating poses a challenge for m ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

Encountering issues with installing angular/cli due to errors popping up

When attempting to install Angular in my terminal after completing the setup, I encountered the following error message: I have already installed: Node v6.10.3 npm ERR! Darwin 17.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g ...

Having trouble updating npm using npm install npm@latest -g and encountering an error?

Encountering errors and warnings while updating npm to the latest version c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External>npm cache clean --force npm WARN u ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Angular patch value not functioning properly after initial use

Whenever I click on the edit icon, I want the form field to populate. It works correctly the first time, but subsequent clicks on different icons do not update it. However, if I hit the cancel button and then click on any edit button again, it works fine. ...

How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created: @Component ({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.css'] }) export class ProgressBarComponent ...

Troubleshooting Angular 2 routes failing to function post aot compilation deployment

Currently, I am implementing RouterModule in my project and have the following configuration in my app.module.ts file: const appRoutes: Routes = [ { path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, { path: 'mainMen ...

Can someone help me figure out how to simulate an express middleware class method using jest and supertest?

I'm facing some challenges trying to achieve the desired outcome when mocking a method in a class using jest and supertest. I'm specifically looking for a solution that can help me bypass the verifyAuthenticated method with a mocked version in or ...