Applying background color within an *ngFor loop

My question may not be perfectly described by the title, but here it is.

In my Angular Material2 project, I have an md-toolbar where I am dynamically looping through values:

<md-toolbar (click)="selectedToolbarValue(key.Name)" *ngFor="let key of arrayOfKeys; let i=index">
       <span>{{key.Name}}</span>
</md-toolbar>

Now, I want to change the background color of a clicked toolbar using [ngClass]. Here's what I've tried:

<md-toolbar [ngClass]="{'toolBarColor':setToolbarStyle}" (click)="selectedToolbarValue(key.Name)" *ngFor="let key of arrayOfKeys; let i=index">
       <span>{{key.Name}}</span>
</md-toolbar>

In my component file:

setToolbarStyle:boolean=false;
selectedToolbarValue(value){
    this.setToolbarStyle = true;
    //other code
}

In my stylesheet:

.toolBarColor{
background-color:blue;
color:#fff;
}

The issue I'm facing is that the above code applies styles to all the toolbar values in the loop. How can I style only the toolbar that is being clicked?

Answer №1

Instead of using a static value in the ngClass expression, you can utilize a function that takes an index or unique identifier:

<md-toolbar [ngClass]="{'toolBarColor':setToolbarStyle(i)}" (click)="selectedToolbarValue(key.Name, i)" *ngFor="let key of arrayOfKeys; let i=index">

toolbarStyleIndex: number;

setToolbarStyle(i) {
    return i===toolbarStyleIndex;
}

selectedToolbarValue(value, i){
    this.toolbarStyleIndex = i;
    //other code
}

Answer №2

To customize the toolbar style based on a boolean property in an array of keys, make the following adjustments:

<md-toolbar [ngClass]="{'toolBarColor': setToolbarStyle(key)}" 
            (click)="selectedToolbarValue(key.Name)" 
            *ngFor="let key of arrayOfKeys; let i=index">        
    <span>{{key.Name}}</span>
</md-toolbar>

Within your component class, implement the setToolbarStyle(key) method:

setToolbarStyle(key:any) : boolean {
    key.setToolbarStyle = true;
    return key.setToolbarStyle;
}

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

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

A guide on triggering a function in Angular 6 when scrolling up or down

Is there a way to trigger a function when a user scrolls up or down in an Angular 6 project? I want to implement a feature similar to fullpage.js in my Angular 6 application. I initially attempted to achieve this using Angular animations, but without succ ...

The Bootstrap image fails to adhere to the size of its parent flex container

I am having trouble positioning an image, heading, and a button on top of another image. The issue arises when viewing the content on small screens as the smaller image fails to resize properly and extends beyond the background of the larger holding imag ...

Utilizing space with margin and padding in Bootstrap 5

I recently started experimenting with bootstrap 5, but I'm feeling quite disoriented. The layout I have created includes some blue elements (borrowed the sidebar from this source) and now I am attempting to replicate this design. https://i.sstatic.ne ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

What steps should be taken to address IE6 problems when a website functions properly in other browsers?

If you come across a website that functions perfectly on all browsers except for IE6, where the layout is extremely distorted but rebuilding the entire markup is not an option. Furthermore, only CSS selectors supported by IE6 are being utilized on the sit ...

How can you ensure an element's height matches its width within an Ionic framework?

I am currently creating an application using the Ionic framework, and I am looking to set a square image as the background. The challenge is to ensure that the image scales appropriately for different screen resolutions; ideally, it should occupy the full ...

Is there a way to adjust the placement of text in an HTML document?

Just starting out with web development and created some HTML code: <html> <body> {errors} <p>Input your numbers:</p> <form method="post" action="."> <p><inpu ...

Creating a loading screen in Angular 4: Insert an item into the HTML and then set it to disappear automatically after

I'm dealing with a loading screen that typically takes between 15-30 seconds to load about 50 items onto the page. The loading process displays each item on the page using the message: Loading item x For each data call made to the database, an obser ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

The process of deploying production-ready code using webpack and angular2

Currently, my Angular 2 code utilizes both webpack and grunt. During development, I rely on webpack-dev-server as a grunt task. When it comes to preparing the code for production deployment, I handle all minification tasks through Grunt which results in t ...

Activate collapsible navigation icon when clicked on a smaller screen

Seeking assistance as a newcomer to coding. Struggling to implement a responsive navbar icon that changes on small screens when clicked. Utilized a bootstrap navbar but encountering issues where clicking the navbar on a small screen only displays the list ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

What is the method for activating a button when a user inputs the correct email address or a 10-digit mobile number

How can I enable a button when the user enters a correct email or a 10-digit mobile number? Here is my code: https://stackblitz.com/edit/angular-p5knn6?file=src%2Findex.html <div class="login_div"> <form action=""> <input type="text" ...

Inquiries for Web-Based Applications

As I contemplate coding my very first webapp, I must admit that my skills are somewhere between beginner and intermediate in html, css, js, jquery, node, sql, and mongodb. However, the challenge lies in not knowing how to bring my vision to life. My ulti ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

What is the best way to continuously loop an image from left to right and right to left indefinitely using JavaScript?

As part of the challenge, I am tasked with creating a Pacman game using HTML, CSS, and JavaScript. One key aspect is to control the movement of the ghosts throughout the game. However, I am facing an issue with the current function that controls the ghost& ...