in dynamic div - on click highlight color

128 views Asked by At

HTML

<div class="nav--small nodeLevel newColor" id="rowItem-{{i}}" *ngFor="let root of rootzTemplates; let i=index" (click)="nodeClickLevel1(root,i)">
    <p style="padding: 19px 1px;color: #fff; text-align: center;">
        {{root}} 
    </p>
</div>

CSS

 .activeColor {
   background-color: grey;
}

JavaScript

constructor(private el: ElementRef) { }
        
nodeClickLevel1(root, id){
     this.myTag = this.el.nativeElement.querySelector("#rowItem-" + id);
     this.myTag.classList.remove('activeColor');
     this.myTag.classList.add('activeColor');
}

Now div is dynamic, say number of div element is 6, on click event i have to change particular clicked div background-color to grey and rest of color should remain same. Now if I click on div say 2, only 2nd div has highlight with grey color, rest of the color should remain same and vice versa.

2

There are 2 answers

0
Piyali Ghosh On

Change your function like this

nodeClickLevel1(root, id){
    this.myTag = root
}

change your template code like this

[class.newColor]="root === myTag"

Hope it will solve your problem.

0
Sinisa Rudan On

Your code can be much simpler, no need for troublesome ElementRef, no need for index ids, etc. So here is the code:

//our root app component
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  // templateUrl: "app.html",
  template: `
    <div class="nav--small nodeLevel newColor" [class.activeColor]="root === myTag" *ngFor="let root of rootzTemplates" (click)="nodeClickLevel1(root)">
            <p style="padding: 19px 1px;color: #fff;    text-align: center;">{{root}}</p>
</div>
  `,
})
export class App {
  name: string;
  constructor() { }
  protected myTag:any;
  public rootzTemplates: any[] = ["first", "2nd", "3rd"];

  nodeClickLevel1(root){
    this.myTag = root;
}
}

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App],
})
export class AppModule {}

and css:

.activeColor {
   background-color: grey !important;
}
.nav--small{
   background-color: black;
}

Here is the working PLNKR link: http://plnkr.co/edit/oRZa3E5WtYpusKHd