简体   繁体   中英

How to apply style in angular6

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

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

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

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"}] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM