leo
leo

Reputation: 3055

change class name on click and remove class on other click - Angular 4

Can some one help me to resolve this. I have table with different columns (TD). I want to select one cell and change its classname. when i click on other cell, i want to restore the classname in previously cell and change the classname on newly selected cell.. Please note: each cell have different classname. So i have to keep track of pervious class and selected element. This is Angular 4 application. my table:

<table class="table package-table stats">
            <tbody>
                <tr *ngIf="deptStatsModel.length>0">
                    <th (click)="setStatsActByDept($event,dt2,null)" class="st-th">ORG</th>
                    <th (click)="setStatsActByDept($event,dt2,'OD')" class="OverDue">Over Due</th>
                    <th (click)="setStatsActByDept($event,dt2,'NA')" class="NeedAttention">Need Att</th>
                    <th (click)="setStatsActByDept($event,dt2,'IA')" class="InProgress">In Prog</th>
                    <th (click)="setStatsActByDept($event,dt2,'CP')" class="Comp">Complete</th>
                </tr>
                <tr *ngFor="let model of deptStatsModel">
                    <td (click)="setActivitiesData($event,model, 'all','DPT')">{{model.deptName}}</td>
                    <td (click)="setActivitiesData($event,model, 'OD','DPT')">{{model.overDue}}</td>
                    <td (click)="setActivitiesData($event,model, 'NA','DPT')">{{model.needAtt}}</td>
                    <td (click)="setActivitiesData($event,model, 'IP','DPT')">{{model.inProg}}</td>
                    <td (click)="setActivitiesData($event,model, 'CP','DPT')">{{model.complete}}</td>
                </tr>
                <tr *ngIf="deptStatsModel.length==0">
                    <td style="text-align: left" colspan="5">No records found</td>
                </tr>
            </tbody>
        </table>

I have on click as below:

setStatsActByDept(event,dt,type)
  {

 var target = event.target || event.srcElement || 
 event.currentTarget;

 this.prevDeptCss=target.cloneNode();
 target.className="selected";

  .........
 }

I dont know what to do next..help please.

Upvotes: 0

Views: 1587

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You're thinking about it in the wrong way. The code shouldn't modify the DOM. It should modify the state of the component. The template is the one responsible to apply CSS classes to DOM elements based on the state of the component.

Assuming, as your code seems to imply, that you want to select the header cells. Your code should simply look like the following.

In your component:

public selectedHeader: string;

In your view:

<th (click)="selectedHeader = 'ORG'" [ngClass]="selectedHeader === 'ORG' ? 'selected' : 'st-th'">ORG</th>
<th (click)="selectedHeader = 'OverDue'" [ngClass]="selectedHeader === 'OverDue' ? 'selected' : 'OverDue'">Over Due</th>
...

Upvotes: 1

Related Questions