Angular: conditional class with *ngClass

后端 未结 19 1959
醉话见心
醉话见心 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:41

    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};
        }
    
    0 讨论(0)
  • 2020-11-22 05:41

    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>
    
    0 讨论(0)
  • 2020-11-22 05:42

    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'"
    
    0 讨论(0)
  • 2020-11-22 05:46

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

    [class.yourClass]="YourCondition"
    
    0 讨论(0)
  • 2020-11-22 05:47

    with the following examples you can use 'IF ELSE'

    <p class="{{condition ? 'checkedClass' : 'uncheckedClass'}}">
    <p [ngClass]="condition ? 'checkedClass' : 'uncheckedClass'">
    <p [ngClass]="[condition ? 'checkedClass' : 'uncheckedClass']">
    
    0 讨论(0)
  • 2020-11-22 05:47

    You can use [ngClass] or [class.classname], both will work the same.
    [class.my-class]="step==='step1'"

       OR

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

    Both will work the same!

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