简体   繁体   English

Angular2中的ng-class

[英]ng-class in Angular2

I am developing a test application in angular 2 and I'm stuck with a problem of adding classes based on list from model. 我正在开发角度为2的测试应用程序,并且遇到了基于模型列表添加类的问题。

In Angular 1 one could do: 在Angular 1中,可以做到:

// model
$scope.myClasses = ['class1', 'class2', ...];

// view
... ng-class="myClasses" ...

In Angular 2, all I have been able to do so far is: 在Angular 2中,到目前为止我只能做的是:

// view
... [class.class1]="true" [class.class2]="true" ...

Which is obviously not very dynamic and I'm sure there must be a better way to do this. 这显然不是很动态,我相信必须有更好的方法来做到这一点。

However, I have also tried: 但是,我也尝试过:

// model
class ... {
    private myClasses: any;
    constructor() {
        this.myClasses = ['class1', 'class2', ...];
    }

// view
... [class]="myClasses" ...

but this doesn't work, I have tried myClasses as a string name of a single class, array of strings, object with a classname key and true as a value, an array of objects of this kind, but sadly, nothing of listed will work this way. 但这是行不通的,我尝试将myClasses作为单个类的字符串名称,字符串数组,带有类名键的对象以及将true作为值的对象,此类对象的数组,但可悲的是,列表中没有任何内容这样工作。

According to the NgClass API docs , Angular 2 will accept a string, an Array, or an Object/map as the expression to NgClass. 根据NgClass API文档 ,Angular 2将接受字符串,数组或对象/映射作为NgClass的表达式。 Or, of course, you could specify a function that returns one of those. 或者,当然,您可以指定一个返回其中一个的函数。

import {Component, CORE_DIRECTIVES} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  directives: [CORE_DIRECTIVES],
  template: `
    <div>
      <h2>{{title}}</h2>
      <div ngClass="gray-border purple">string of classes</div>
      <div [ngClass]="'gray-border purple'">string of classes</div>
      <div [ngClass]="['gray-border', 'green']">array of classes</div>
      <div [ngClass]="{'gray-border': true, 'blue': true}">object/map of classes</div>
      <button [ngClass]="{active: isActive}" (click)="isActive = !isActive">Click me</button>
    </div>
  `,
  styles: [`
    .gray-border {  border: 1px solid gray; }
    .blue   { color: blue; }
    .green  { color: green; }
    .purple { color: purple; }
    .active { background-color: #f55; }
  `]
})
export class App {
  title = "Angular 2 - NgClass";
  isActive = false;
}

Plunker 柱塞

If you are passing a literal string, note the two alternative syntaxes: 如果要传递文字字符串,请注意以下两种语法:

<div ngClass="gray-border purple">string of classes</div>
<div [ngClass]="'gray-border purple'">string of classes</div>

I believe the first is just syntactic sugar for the second. 我相信第一个只是语法糖,第二个只是语法糖。

And to quote the docs: 并引用文档:

While the NgClass directive can interpret expressions evaluating to string, Array or Object, the Object-based version is the most often used and has an advantage of keeping all the CSS class names in a template. 虽然NgClass指令可以解释以字符串,数组或对象为单位的表达式,但基于对象的版本是最常用的,并且具有将所有CSS类名保留在模板中的优点。

You must specify CSSClass in directives property of @View decorator. 您必须在@View装饰器的directives属性中指定CSSClass Check out this plunk . 看看这个普拉克

@Component({
    selector: 'app',
})
@View({
    template: '<div [class]="classMap">Class Map</div>',
    directives: [CSSClass]
})
class App {
    constructor() {
        this.classMap = { 'class1': true, 'class2': false };

        setInterval(() => {
            this.classMap.class2 = !this.classMap.class2;
        }, 1000)
    }
}

UPD UPD

CSSClass was renamed to NgClass in alpha-35. CSSClass在alpha-35中被重命名NgClass See this plunk 看到这个pl

@Component({
  selector: 'app',
})
@View({
  directives: [NgClass],
  template: `
    <div [ng-class]="classMap">Class Map</div>
  `,
})
class App { /* ... */ }

One more method [ Using Ternary Operator and Interpolation] 一种方法 [使用三元算子和插值]

(Altough Mark Rajcok stated all possible ngClass methods, but you can couple it with ternary operator and you get else condtions) (尽管Mark Rajcok陈述了所有可能的ngClass方法,但是您可以将其与ternary operator并获得else条件)


Template 模板

<div class="hard-coded-class {{classCondition ? 'c1 c2': 'c3 c4'}}">
    Conditional classes using <b>Ternary Operator</b>
</div>

or use ternary operator with ngClass , see how 或对ngClass使用ternary operator请参阅

TS TS

export class App {
  this.classCondition = false;
}

Result 结果

<div class="hard-coded-class c3 c4">
      Conditional classes using <b>Ternary Operator</b>
</div>

Hope it helps someone. 希望它可以帮助某人。

Using typescript and Angular 2 beta, ngClass doesn't seem to work. 使用typescript和Angular 2 beta,ngClass似乎不起作用。 From following the API preview - https://angular.io/docs/ts/latest/api/common/NgClass-directive.html 通过遵循API预览-https: //angular.io/docs/ts/latest/api/common/NgClass-directive.html

template: '<div [ngClass]="classMap">Class Map</div>'

The example from Google provides two versions of code (which I assume is Alpha and updated to Beta). Google的示例提供了两个版本的代码(我认为是Alpha,并已更新为Beta)。 The new syntax in the website example doesn't seem to work... any ideas? 网站示例中的新语法似乎不起作用...有什么想法吗?

@View({
    template: `
        <div class="container questions">
            <div class="row formSection">
                 <h2>
                     <div [ngClass]="completed">completed</div>
                </h2>
                <questionSection></questionSection>
            </div>
        </div>
        `,
        directives: [NgClass, QuestionSection],
})

I was trying to do something similar, I had a list of menu items and wanted to specify a fontawesome class for each item. 我试图做类似的事情,我有一个菜单项列表,想为每个项指定一个fontawesome类。 This is how I made it work. 这就是我的工作方式。 In my typescript component I had this: 在我的打字稿组件中,我有以下内容:

    export class AppCmp {
       menuItems = [
         {
           text: 'Editor',
           icon: 'fa fa-pencil'
         },
         {
           text: 'Account',
           icon: 'fa fa-user'
         },
         {
           text: 'Catalog',
           icon: 'fa fa-list'
         }
      ]
    }

Then in my html: 然后在我的html中:

  <div *ngFor="#item of menuItems; #index = index">
        <i [attr.class]="item.icon"></i>
        <span>{{ item.text }}</span>
  </div>

Here is the plunker, https://plnkr.co/edit/PIDRZsc7ZhISNgZzOWuY?p=preview Hope that helps 这是the车手, https: //plnkr.co/edit/PIDRZsc7ZhISNgZzOWuY p = preview希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM