Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked

     <nav class="navbar ">
        <ul class="navbar-nav">
          <li *ngFor="let item of items">
         <a class="nav-link" >{{item.title}}</a>
          </li>
        </ul>
      </nav>


items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]

Controller:

private name;

this.routes.params.subscribe((params)=>{
      this.data=params['id'];
      console.log(this.data);
    })  

this.Service.getAllItems().subscribe((data)=>{
   this.items=data;
   for(let i of this.items){
   if(i.id == this.data){
   this.name=i.title;
}
}

I need to change the text color to red when a specific ID is clicked. Can anyone help with how to achieve this?

Answer №1

Create a variable to store the active ID after clicking:

import { Component } from '@angular/core';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
     public activeId;

      setIdActive(id) {
        this.activeId = id;
      }

    }

In your HTML:

<nav class="navbar ">
        <ul class="navbar-nav">
          <li *ngFor="let item of items">
         <a (click)="setIdActive(item.id)" class="nav-link" [ngClass]="{'apply-color': item.id == activeId}" >{{item.title}}</a>
          </li>
        </ul>
</nav>

apply-color is a CSS class that sets the desired color.

Answer №2

This response is tailored to situations where we need to emphasize all the options that have been selected.

If you wish to alter the color of all clicked links, rather than just the most recent one, I recommend utilizing a HostListener directive.

constructor(private elem: ElementRef, private renderer: Renderer) { }

@HostListener('click',['$event'])  //in this scenario, the event parameter can be omitted
Click(event: Event) {
    this.renderer.setElementStyle(elem.nativeElement, 'color', 'red');
}

If using just the CSS style for a:visited suits your needs (though not personally tested), it may be the optimal solution.

Answer №3

To solve this issue, use the [ngClass] directive. When the link is clicked, pass the item to the function to change the activeId and apply the class using [ngClass] to the link.

let activeId:number;

makeALinkActive(item){
this.activeId = item.id;
}

items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]
.red{
color: red;
}
<nav class="navbar ">
    <ul class="navbar-nav">
       <li *ngFor="let item of items">
          <a class="nav-link" [ngClass]="{'red':activeId === item.id}" (click)='makeALinkActive(item)'>{{item.title}}</a>
       </li>
    </ul>
 </nav>

items=[{id:1,title:"a"},{id:2,title:"b"},{id:2,title:"c"},{id:3,title:"d"}]

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

Discover the benefits of utilizing router.back() cascade in Next/React and how to effectively bypass anchor links

Currently, I am working on developing my own blog website using Next.js and MD transcriptions. The issue I am facing involves anchor links. All the titles <h1> are being converted into anchor links through the use of the next Link component: <Link ...

Animating a div in CSS3 to expand horizontally from left to right without affecting its original position

I am currently in the process of developing a calendar using HTML, CSS, and JavaScript. The main purpose of this calendar is to showcase upcoming and past events. However, I am facing difficulties in ensuring that my event blocks occupy the remaining space ...

What is the process of assigning attribute values conditionally in Angular 2?

I'm currently exploring Angular 2 and facing a challenge with a basic material input tag. I want to dynamically set its value based on a condition. <md-input value="dataSelected ? {{selectedDataName}} : ''"></md-input> I attemp ...

Why isn't setInterval set to a duration of one thousand milliseconds?

While trying to use some code from w3schools, I noticed that the setInterval in the example is set to 5 instead of 5000. Shouldn't it be in milliseconds? If not, how can I speed up this animation? When I try reducing it to decimals like 0.01, the anim ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Angular Material's <mat-select> element can trigger a function to execute when it loses focus

I'm trying to add functionality to a <mat-select> element so that a function is executed when the element loses focus. Currently, the function only executes on selection change: <mat-form-field fxFlex> <mat-label>SSR Status</m ...

The uniform height of flex columns was spoiled by a child element with a display setting of flex

CSS: * { padding: 0; margin: 0; box-sizing: border-box; } body { display: flex; background-color: #F5F5F5; } body > header { display: flex; position: fixed; width: 100%; height: 60px; align-items: center; background-color: #373737 ...

What is the method for bypassing libraries while troubleshooting Angular code in Visual Studio Code?

While debugging my Angular project, I keep getting into @angular/core and ts-lib which are large files with many steps. Is there a way to skip over external code during the debugging process? Below is my launch.json configuration: "version": &qu ...

What is the best way to refresh or reload a child component in Angular?

I have a transaction.component.html file that displays the app-deal-partners component. Every time the delete function is triggered, I want to refresh and reload the child component, which is the app-deal-partners component. I need to reload <app-deal- ...

Enhancing List Numbers with CSS Styling

Is there a way to customize the appearance of numbered lists? I created an ordered list and would like to modify the numbering style To remove the bullets And adjust the color and background ...

Retrieve a targeted tag from the API snippet

I need to extract the IMG SRC tag from the given code: <pod title="Scientific name" scanner="Data" id="ScientificName:SpeciesData" position="200" error="false" numsubpods="1"> <subpod title=""> <plaintext>Canis lupus familiaris</plain ...

Displaying SQL data in a table using PHP

I've encountered a dilemma where the category name is being outputted as the same for both offered and wanted categories in PHP. This issue arises when trying to display categoryName differently for each type of category in a table. Despite attempting ...

Using CSS3 gradient in grey instead of white

I came across an amazing example by Chris Coyier showcasing a "read more" button. I attempted to replicate this by creating a simple fadeout effect from white to transparent, but unfortunately, I ended up with a grey gradient instead. You can view my atte ...

Tips for enhancing the flexibility of the owl carousel

I've been trying to make four items fit on a medium screen and two on a mobile device, but no matter what I do - adjusting widths, heights, columns, and responsive classes like col-6, col-md-3, col-lg-3 - nothing seems to work well. I could really use ...

Using Jquery to update the information displayed in a div class to show more details about the clicked video

I am currently developing a video playlist similar to YouTube for my hybrid app. I am fetching and displaying the data using functions from json data provided by the web server. Below is a sample of the json data: [{"video_id":"1","video_youtube_title":" ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...

Steps for sending angular form data to a .Net backend that requires an autoincrement id:

When trying to insert data into an SQL database through a .Net API endpoint, I encountered an issue with the request body specifying that the ID is auto-incremental. Status 500: Cannot insert explicit value for identity column in table 'StockFeed&ap ...

Difficulty encountered with changing font color on CSS

I'm having trouble fixing the text color, it's currently white and blending in with the background. I've set the color to #1a6eb6 for both the TEXT element and the submenu list items, but it's not working. Can someone assist me with thi ...

Display the table once the radio button has been selected

Before we proceed, please take a look at the following two images: image 1 image 2 I have over 20 fields similar to 'Image 1'. If "Yes" is selected, then a table like in 'Image 2' should be displayed. This means I have 20 Yes/No fields ...

Having trouble with linking an external JavaScript file inside the head tag?

I've connected my script.js file to my index.html file, and both files are located in the same directory. I initially linked the script.js file in the <head> section, but it wasn't working as expected. Upon checking the console, I encounter ...