rakibtg rakibtg - 21 days ago 6
AngularJS Question

Angular 2 - changing css selector on click

Here is my ng2 app,

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

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div class="{{item.itemclass}}" id="lists" *ngFor="let item of items">
<div class="item" (click)="selectItem(item)">{{item}}</div>
<div>{{item.itemclass}}</div>
</div>
</div>
`,
})

export class App {
name:string;
items: any[];
itemclass : string;
constructor() {
this.name = 'Angular2';
this.items = [
'lorem',
'ipsum',
'sit',
'trump :D'
];
this.itemclass = '';
}
selectItem(item){
console.log(item);
item.itemclass = "active";
}
}

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


When I am triggering an click event
selectItem
and trying to change the
itemclass
it has no effect.

Find my app at Plunker.

All i want to achive is when a user clicks on a item it would have an
active
css selector, and when i would click another item it would simple toggle and all the siblings will not have the
active
css class anymore.

But its not working how i am trying it to be. How to do it in ng2?

Answer

Here is your requirement. Please check the plunker in the question.

Here, I used, [class.active]="item == itemclass", this binds the class name active to the current selected item.

these [class.active] [], brackets are one way binding from controller to view.

this.itemclass = item; this line assigns the current item to item class, which we checked in the view.

Component:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div id="lists" *ngFor="let item of items">
        <div class="item" [class.active]="item == itemclass" (click)="selectItem(item)">{{item}}</div>
        <div>{{item.itemclass}}</div>
      </div>
    </div>
  `,
})

Class:

export class App {
  name:string;
  items: any[];
  itemclass : string;
  constructor() {
    this.name = 'Angular2';
    this.items = [
      'lorem',
      'ipsum',
      'sit',
      'trump :D'
    ];
    this.itemclass = '';
  }
  selectItem(item){

    this.itemclass = item;
    console.log(this.itemclass);
  }
}

Here is the solved plunker link.

Comments