Angular 2通过插值将值添加到ngClass [英] Angular 2 add value to ngClass with interpolation

查看:94
本文介绍了Angular 2通过插值将值添加到ngClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我在数组中有一些对象(我们称其为数组"items"),如{ title: "Title", value: true },而我使用ngFor将它们显示为:

Lets say I have some objects in an array (lets call the array "items") like { title: "Title", value: true } and I use ngFor to display them like:

<h1 *ngFor="let item of items">{{ item.title }}</h1>

现在让我说我想根据item.value是true还是false在h1上显示一个类. 我怎样才能做到这一点?

Now lets say I want to display a class on the h1 based on if item.value is true or false. How can I do that?

我无法添加[class.some-class]="{{ item.value }}".基本上,如何将当前项目的true或false值转换为ngClass之类的值?我是否在Angular 2中缺少一种明显的方法?

I can't add [class.some-class]="{{ item.value }}". Basically, how can I get the true or false value for the current item into something like ngClass? Am I missing an obvious way to do this in Angular 2?

(顺便说一句,我知道我可以通过在h1中添加class="{{ item.value | pipe }}"并传递值并基于true和false值返回正确的类来做到这一点,但是似乎应该有更好的方法.)

(Btw, I know I can do it by adding class="{{ item.value | pipe }}" to the h1 and piping the value and returning the correct class based on the values true and false, but it seems like there should be a better way.)

谢谢

推荐答案

您可以添加这样的条件类:

You can add a conditional class like this:

<h1 *ngFor="let item of items" 
     [class.some-class]="item.value === true">
     {{ item.title }}
</h1>

请记住,*ngFor语法实际上扩展为template.在您的示例中,它将扩展为:

Remember that the *ngFor syntax actually expands into a template. In your example, it would expand into:

<template ngFor let-item [ngForOf]="items">
    <h1 [class.some-class]="item.value === true">
       {{ item.title }}
    </h1>       
</template>

看到它展开时,可以看到为什么能够将[class.xyz]指令与item的模板输入变量一起使用.

When you see it expanded, you can see why you're able to use the [class.xyz] directive with a template input variable of the item.

这篇关于Angular 2通过插值将值添加到ngClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆