I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images.

If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select.

This is the component in question:

<div *ngFor="let item of data; let i = index;" (click)="setRow(i)" 
    [ngClass]="{'highlight': selectedIndex===i}" class="cycleHover"
>
    {{item}}
</div> 

CSS:

.cycleHover{
    cursor: pointer;
    padding: 5px 20px;
    margin: 4px;
    font-style: normal;
    font-weight: 700;
    font-size: 14px;
    // line-height: 18px;

    color: #010103;
}

.highlight{ 
    background-color: #fff;
    padding: 5px 20px;
    margin: 4px;
    color: #737D88;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.05);
    border-radius: 24px;
}

Typescript:

selectedIndex: any;

data: any[] = ["D", "W", "M", "Q", "Y"];

 setRow(_index: number) {
    this.selectedIndex = _index;
  }

Answer №1

If you want to write cleaner and more concise code, consider following this pattern:

<div *ngFor="let item of data" 
    (click)="selected = data" 
    [class.highlight]="selected === data"
    class="cycleHover"
>
    {{item}}
</div> 
data = ["D", "W", "M", "Q", "Y"];
selected = this.data[0]; // You can also set it to undefined

Answer №2

To set the default selection to the first item, update the declaration of selectedIndex in your TypeScript file as shown below:

selectedIndex:number=0;

Answer №3

To set the middle as the default selection, include the following code in the ngOnInit() method:

this.setDefaultRow(Math.floor(this.data.length/2));

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

Instructions on activating the standard scrolling function for a specific DIV element

I'm struggling to achieve a specific scrolling effect on my one-page website. I want the initial section to be displayed as a full page, and when the user scrolls down, it should transition to the next section with a full page scroll. However, once th ...

I am not currently working on developing an angular application

Seeking assistance for the issue described below, as I have been struggling with it for three days. Any help would be greatly appreciated. Despite multiple attempts, the situation only seems to worsen with each try. The problem arises when attempting to ...

Breaking down a large array in Node.js to initiate multiple API calls

I am currently faced with a challenge where I have a CSV file containing 21k records, with each record being a single alphanumeric word. I need to process these records by sending them to an API in JSON key-value pair format. The API can only accept 500 el ...

Error message displaying Angular Service not able to be injected into component: StaticInjectorError in AppModule

I'm currently attempting to inject a SpotifyService service into a SearchComponent component, where the service requires Http as a parameter. Below is my module setup: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], decla ...

Trouble ensues when using a scaled THREE.Sprite with THREE.Raycaster

My goal is to implement the use of THREE.Raycaster in order to display an html label whenever a user hovers over an object. The functionality works properly when using THREE.Mesh, however, with THREE.Sprite, I am noticing a strange spacing issue that seems ...

Retrieving the output of a parent computed method in VueJS, using a child component

I am facing difficulties in passing the dynamically changing value of a computed method to my child component. I am creating a button component with different save states, but the button always remains stuck on one state and does not update according to th ...

Combining CSS documents

In order to improve page load speed, I need to consolidate multiple CSS files into one large file. Will the styles function properly if I merge them all together, or are there potential issues when combining multiple CSS files? My software is built in Ja ...

Can const variables be reassigned in JavaScript programming?

Can you reassign a const variable in JavaScript? In C++, we can cast variables to and from const. Is there something similar in JavaScript? My question is const a = 1; unconst(a); a = "xyz"; a === "xyz" // true I'm not referring to object prope ...

Content that sticks to the footer

I've been utilizing the sticky footer solution found at: This is how the CSS appears: * { margin: 0; } html, body { height: 100%; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -4em; } .footer, .push { height: 4 ...

Display the input value in AngularJS in a customized format without changing the format in the model

When receiving an integer indicating a duration in minutes, I want to display it as hours or days if it exceeds a certain value. The ng-model should still keep the value in minutes so that any user changes are reflected accurately. For example: Reading & ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Experiencing an issue while rendering due to the presence of display: table-cell;

I am currently in the process of developing a website. The HTML Header section is structured as follows: <div id="page"> <header> <a href="#" class="redsquare">&nbsp;</a> <div class="head-wrapper"> ...

The animation of the background color over an image appears glitchy when viewed on Safari

I've been attempting to create an animation that changes the background color over an image. Everything seems to be working fine on all browsers and operating systems except for Safari on macOS. I've searched extensively on SO and Google but have ...

Publishing Typescript to NPM without including any JavaScript files

I want to publish my *.ts file on NPM, but it only contains type and interface definitions. There are no exported JavaScript functions or objects. Should I delete the "main": "index.js" entry in package.json and replace it with "main": "dist/types.ts" inst ...

Experiencing difficulties integrating react-moveable with NEXTjs: Error encountered - Unable to access property 'userAgent' as it is undefined

I've been grappling with this problem for the past few hours. I have successfully implemented react-moveable in a simple node.js app, but when I attempt to integrate it into a NEXTjs app, an error crops up: TypeError: Cannot read property 'userAg ...

Error: Unable to access the property 'fn' of an undefined object in electron version 2 using Angular 6

I am currently utilizing Angular 6.0.3 and electronjs 2.0.2 with the package.json configuration shown below: { "name": "test", "version": "1.0.0", "license": "MIT", "main": "electron-main.js", "author": { "name": "Moh ...

Can you tell me about the feature called "Inspect Browser" box?

Can you identify the significance of this enigmatic purple box while inspecting elements in the browser's developer tools? It does not correspond to padding, margins, or borders, yet it seems to be occupying space within the designated div. [1]: http ...

"Clicking on a child link within a Bootstrap5 dropdown causes the dropdown menu

I integrated a dropdown feature to create a navigation menu. The issue I encountered is that when I expand a heading and click on a sublink, the menu collapses instead of redirecting me to the intended link. I suspect this has something to do with the co ...

Is there a way I can create a conditional statement to determine the values of my selection?

I need to customize the order status values for 'confirmed', 'on the way' and 'delivered'. How can I map these statuses to specific numerical values based on the options available in a select menu? Confirmed - 10 On the way - ...