Angular add class dynamically

前端 未结 3 1245
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 04:05

Is there a way to add a class from the .ts file, using Angular solutions

I want to d

相关标签:
3条回答
  • 2021-02-08 04:31

    While the solution with the Renderer works, I am proposing you create a data structure for your buttons

    buttons: Array<{label: string}> = [
        {
          label: 'Global'
        },
        {
          label: 'Maintenance'
        },
        {
          label: 'Settings'
        },
        {
          label: 'Profile'
        },
        {
          label: 'Transactions'
        }
      ]
    

    This can easily be iterated through using ngFor

    <button 
      *ngFor="let button of buttons" 
      class="general" 
      (click)="ChangeScreen(button.label)" 
      [class.selected]="CurrentPage == button.label">
      {{ button.label }}
    </button>
    

    And only thing your ChangeScreen method would need is... the thing its already doing, setting the current page!

    See stackblitz for an example of how this plays out.

    0 讨论(0)
  • 2021-02-08 04:32

    Use Renderer

    See here:https://angular.io/api/core/Renderer

    and here:https://angular.io/api/core/Renderer#setElementClass

    import { Renderer } from '@angular/core';
    
    constructor(private render:Renderer) { }
    
    ChangeScreen(event:any) {
     this.renderer.setElementClass(event.target,"selected",true);
    }
    

    In html:

    <button class="general" (click)="ChangeScreen()">Global</button>
    

    Or Render2:

    See here:https://angular.io/api/core/Renderer2

    and here:https://angular.io/api/core/Renderer2#addClass

    import { Renderer2 } from '@angular/core';
    
    constructor(private render:Renderer2) { }
    
    ChangeScreen(event:any) {
     this.renderer.addClass(event.target,"selected");
    }
    

    In html:

    <button class="general" (click)="ChangeScreen()">Global</button>
    
    0 讨论(0)
  • 2021-02-08 04:33

    You can use ngClass directive:

    <div id="mydiv" [ngClass]="{'myCSSclass' : condition}"></div>
    

    Simple as that! myDiv will have the class myCSSclass only when the condition evaluates to true. This condition can be set in your typescript file or in the template.

    0 讨论(0)
提交回复
热议问题