0

I need to set different classes depending of the Button. Example:

delete -> class='danger';

edit -> class='primary' (setted by default)

This is my HTML:

<div class="container">
  <table class="table">
    <tr>
      <th *ngFor="let col of columns" (click)="sortTable(col)">{{col}}</th>
      <th>Actions</th>
    </tr>
    <tr *ngFor="let user of users | paginate: {itemsPerPage: 5,
                                               currentPage: page,
                                               totalItems: users.length } ; let i = index">
      <td *ngFor="let col of columns">{{user[col]}}</td>
      <td>
        <button class="btn btn-{{class}}" *ngFor="let act of actions" (click)="actionFunc(act,i)">{{act}}</button>
        //THE RESULT MUST BE LIKE THIS
        <!--<button class="btn btn-danger">Delete</button>-->
        <!--<button class="btn btn-primary"> Edit</button>-->
      </td>
    </tr>
  </table>
</div>

<div>
  <pagination-controls (pageChange)="page = $event"></pagination-controls>
</div>

This is my component.ts:

import {Component, Input, OnInit} from '@angular/core';

@Component({
  selector: 'app-dynamic-table',
  templateUrl: './dynamic-table.component.html',
  styleUrls: ['./dynamic-table.component.css']
})
export class DynamicTableComponent implements OnInit {
  @Input()
  users = [];
  @Input()
  columns: string[];
  @Input()
  actions: string[];

  @Input()
  class = 'primary';

  direction = false;
  page: any;

  constructor() {
  }

  sortTable(param) {
    /*...*/
  }

  actionFunc(i, index) {
    if (i === 'deleteUser') {
      if (confirm('Are you sure you want to delete this item?') === true) {
        this.users.splice(index, 1);
      }
    }
    if (i === 'editUser') {
      /*...*/
    }
  }

  ngOnInit(): void {
    /*if (this.actions ==='deleteUser') {
      this.class = 'danger';*/ SOMETHING LIKE THIS
    }
  }

}

I'm not sure if I have to insert the logic inside "onInit()" so If you any suggestion I would appreciate it.

3
  • 1
    You should use NgClass when you're expecting multiple classes to be potentially added. But I don't think adding buttons dynamically like that is necessary, I'd add them all and hide or disable accordingly. Commented Mar 4, 2019 at 14:52
  • Yeah, I know is not necessary. I'm new in Angular and my task in this moment is this, just for training. Can you write an example of function or ngClass that you would use? Commented Mar 4, 2019 at 14:55
  • ok, I did it, changing class with ngClass, I will update the question with my solution. Thank you! Commented Mar 4, 2019 at 14:58

2 Answers 2

1

UPDATE HTML

<button [ngClass]="getClassCondition(act)" *ngFor="let act of actions" (click)="actionFunc(act,i)">{{act}}</button>

COMPONENT.TS

 getClassCondition(act) {
    return act === 'deleteUser'  ? this.class = 'btn btn-danger' : 'btn btn-primary' ;
  }
Sign up to request clarification or add additional context in comments.

Comments

0

Add an enum for your Actions:

enum Action {
    'Delete' = 'delete',
    'Edit' = 'primary',
    // etc...
}

Add a function to get the class from enum:

getActionClass(action: string): string {
    return Action[action];
} 

Get the class from the template:

<button class="btn btn-{{getActionClass(act)}}"
        *ngFor="let act of actions"
        (click)="actionFunc(act,i)">{{act}}
</button>

This is a simple example. Bear in mind function calls in template are not the smartest ideas since they get called on every change detection run.

Another idea is to use setter on actions Input:

    _actions: string[];
    @Input('actions')
    set actions(actions) {
        this._actions = actions;
        this._actionsWithClasses = this._actions.map(action => {
            return { action: action, class: Action[action] };
        });
    }
    get actions() {
        return this._actions;
    }

    _actionsWithClasses: { action: string; class: string }[];

... and then use actionsWithClasses in the template instead of actions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.