0

I want to apply text color when expected id will 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;
}
}

For clicked id I have to apply text color red.How to apply it.Please help

developer.PT
  • 660
  • 1
  • 5
  • 11

3 Answers3

1

You could have a variable with the active id, which is set when you click:

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;
      }

    }

And 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 it's a class with the color you want

0

This answer caters to condition where we need to highlight all the options which are clicked

If you want to change the color of all the links which are clicked and not just the last one, I advise you to use a HostListener directive.

consructor(privte elem: ElementRef, private renderer: Renderer) { }

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

And if just the CSS style for a:visited works for you (not tried by myself), it would be the best solution

Saksham
  • 9,037
  • 7
  • 45
  • 73
0

You can you [ngClass] for this problem. When you click the link pass the item to the function. this will change the activeId. By using [ngClass] the class will apply 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"}]