Angular: conditional class with *ngClass

后端 未结 19 1958
醉话见心
醉话见心 2020-11-22 05:21

What is wrong with my Angular code? I am getting:

Cannot read property \'remove\' of undefined at BrowserDomAdapter.removeClass ...

相关标签:
19条回答
  • 2020-11-22 05:23

    Try Like this..

    Define your class with ''

    <ol class="breadcrumb">
        <li *ngClass="{'active': step==='step1'}" (click)="step='step1; '">Step1</li>
        <li *ngClass="{'active': step==='step2'}"  (click)="step='step2'">Step2</li>
        <li *ngClass="{'active': step==='step3'}" (click)="step='step3'">Step3</li>
    </ol>
    
    0 讨论(0)
  • 2020-11-22 05:28

    You should use something ([ngClass] instead of *ngClass) like that:

    <ol class="breadcrumb">
      <li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
      (...)
    

    0 讨论(0)
  • 2020-11-22 05:30

    Additionally, you can add with method function:

    In HTML

    <div [ngClass]="setClasses()">...</div>
    

    In component.ts

    // Set Dynamic Classes
      setClasses() {
        let classes = {
          constantClass: true,
          'conditional-class': this.item.id === 1
        }
    
        return classes;
      }
    
    0 讨论(0)
  • 2020-11-22 05:31

    Angular version 2,...,9 provides several ways to add classes conditionally:

    type one

    [class.my-class]="step === 'step1'"
    

    type two

    [ngClass]="{'my-class': step === 'step1'}"
    

    and multiple option:

    [ngClass]="{'my-class': step === 'step1', 'my-class2':step === 'step2' }"
    

    type three

    [ngClass]="{1:'my-class1',2:'my-class2',3:'my-class4'}[step]"
    

    type four

    [ngClass]="(step=='step1')?'my-class1':'my-class2'"
    
    0 讨论(0)
  • 2020-11-22 05:31

    This is what worked for me:

    [ngClass]="{'active': dashboardComponent.selected_menu == 'profile'}"
    
    0 讨论(0)
  • 2020-11-22 05:33

    Another solution would be using [class.active].

    Example :

    <ol class="breadcrumb">
        <li [class.active]="step=='step1'" (click)="step='step1'">Step1</li>
    </ol>
    
    0 讨论(0)
提交回复
热议问题