我的Angular代码出了什么问题?我得到以下错误:

无法读取BrowserDomAdapter.removeClass中未定义的属性“remove”

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

当前回答

另一个解决方案是使用[class.active]。

例子:

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

其他回答

Angular version 2+提供了几种有条件地添加类的方法:

1型

    [class.my_class] = "step === 'step1'"

两个类型

    [ngClass]="{'my_class': step === 'step1'}"

并有多种选择:

    [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"

三个类型

    [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"

四个类型

    [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

您可以在文档页上找到这些示例

<div class="collapse in " [ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''" id="collapseExampleOrganization" aria-expanded="true" style=""> <ul> <li class="nav-item" [ngClass]="{'active': active_tab=='manage'}"> <a routerLink="/main/organization/manage" (click)="activemenu('manage')"> <i class="la la-building-o"></i> <p>Manage</p></a></li> <li class="nav-item" [ngClass]="{'active': active_tab=='assignservice'}"><a routerLink="/main/organization/assignservice" (click)="activemenu('assignservice')"><i class="la la-user"></i><p>Add organization</p></a></li> </ul></div>

代码是ngClass if else条件的好例子。

[ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''"

[ngClass]="{'active': active_tab=='assignservice'}"

你可以使用ngClass有条件地应用类名,也可以不在Angular中应用

例如

[ngClass]="'someClass'">

有条件的

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

多个条件

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

方法表达

[ngClass]="getSomeClass()"

该方法将在组件内部

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

该指令有三种不同的操作方式,这取决于表达式的计算结果是三种类型中的哪一种:

If the expression evaluates to a string, the string should be one or more space-delimited class names. If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name. If the expression evaluates to an array, each element of the array should either be a string as in type 1 or an object as in type 2. This means that you can mix strings and objects together in an array to give you more control over what CSS classes appear. See the code below for an example of this.

    [class.class_one] = "step === 'step1'"

    [ngClass]="{'class_one': step === 'step1'}"

对于多个选项:

    [ngClass]="{'class_one': step === 'step1', 'class_two' : step === 'step2' }" 

    [ngClass]="{1 : 'class_one', 2 : 'class_two', 3 : 'class_three'}[step]"

    [ngClass]="step == 'step1' ? 'class_one' : 'class_two'"

让,YourCondition是你的条件或布尔属性,然后像这样做

[class.yourClass]="YourCondition"