Angular: conditional class with *ngClass

≯℡__Kan透↙ 提交于 2019-11-25 23:45:33

问题


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

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

HTML

<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>

回答1:


Angular 2,..,7 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'"



回答2:


[ngClass]=... instead of *ngClass.

* is only for the shorthand syntax for structural directives where you can for example use

<div *ngFor="let item of items">{{item}}</div>

instead of the longer equivalent version

<template ngFor let-item [ngForOf]="items">
  <div>{{item}}</div>
</template>

See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

See also https://angular.io/docs/ts/latest/guide/template-syntax.html

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>



回答3:


Another solution would be using [class.active].

Example :

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



回答4:


That's the normal structure for ngClass is:

[ngClass]="{'classname' : condition}"

So in your case, just use it like this...

<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>



回答5:


with the following examples you can use 'IF ELSE'

<p class="{{condition ? 'checkedClass' : 'uncheckedClass'}}">
<p [ngClass]="condition ? 'checkedClass' : 'uncheckedClass'">
<p [ngClass]="[condition ? 'checkedClass' : 'uncheckedClass']">



回答6:


You can use ngClass to apply the class name both conditionally and not in Angular

For Example

[ngClass]="'someClass'">

Conditional

[ngClass]="{'someClass': property1.isValid}">

Multiple Condition

 [ngClass]="{'someClass': property1.isValid && property2.isValid}">

Method expression

[ngClass]="getSomeClass()"

This method will inside of your component

 getSomeClass(){
        const isValid=this.property1 && this.property2;
        return {someClass1:isValid , someClass2:isValid};
    }



回答7:


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

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




回答8:


In Angular 7.X

The CSS classes are updated as follows, depending on the type of the expression evaluation:

  • string - the CSS classes listed in the string (space delimited) are added

  • Array - the CSS classes declared as Array elements are added

  • Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>



回答9:


While I was creating a reactive form, I had to assign 2 types of class on the button. This is how I did it:

<button type="submit" class="btn" [ngClass]="(formGroup.valid)?'btn-info':''" 
[disabled]="!formGroup.valid">Sign in</button>

When the form is valid, button has btn and btn-class (from bootstrap), otherwise just btn class.




回答10:


to extend MostafaMashayekhi his answer for option two> you can also chain multiple options with a ','

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

Also *ngIf can be used in some of these situations usually combined with a *ngFor

class="mats p" *ngIf="mat=='painted'"



回答11:


ngClass syntax:

[ngClass]="{'classname' : conditionFlag}"

You can use like this:

<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>



回答12:


This is what worked for me:

[ngClass]="{'active': dashboardComponent.selected_menu == 'profile'}"



回答13:


Let, YourCondition is your condition or a boolean property, then do like this

[class.yourClass]="YourCondition"



回答14:


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;
  }



回答15:


Not relevant with [ngClass] directive but I was also getting the same error as

Cannot read property 'remove' of undefined at...

and I thought to be the error in my [ngClass] condition but it turned out the property I was trying to access in the condition of [ngClass] was not initialized.

Like I had this in my typescript file

element: {type: string};

and In my [ngClass] I was using

[ngClass]="{'active', element.type === 'active'}"

and I was getting the error

Cannot read property 'type' of undefined at...

and the solution was to fix my property to

element: {type: string} = {type: 'active'};

Hope it helps somebody who is trying to match a condition of a property in [ngClass]



来源:https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!