我在中继器中有一个HTML元素,我想根据四个条件更改类。该条件基于 JSON 中的属性。这个属性叫做type
,我正在使用的css类是red
、blue
、green
。条件是:
- 如果
type
= 红色,则分配 css 类red
- 如果
type
= 蓝色,则分配 css 类blue
- 如果
type
= 绿色,则分配 css 类green
- 如果未定义
type
或为 null,则分配 css 类red
凭借我对AngularJS的有限经验,我知道我可以使用ng-style
属性设置条件CSS。我将如何使用Aurelia实现这一目标?
示例 HTML 标记
<div repeat.for="item of projects" class="col-lg-6">
<div class="card-header">
<!-- I want to change the css class red based on the value of the JSON attribute type -->
<div class="component-type red">
...
</div>
</div>
...
</div>
对类元素使用字符串内插。
<div repeat.for="item of projects">
<div class="${item.type || 'red'}">...</div>
</div>
在此处查看工作忍者神龟要点:https://gist.run/?id=3a588b94a6b8d12666ba4f64645270aa
你可以简单地做:
<div repeat.for="item of projects" class="col-lg-6">
<div class="card-header">
<!-- I want to change the css class red based on the value of the JSON attribute type -->
<div class="component-type ${ item.type == undefined ? 'red' : item.type}">
...
</div>
</div>
...
或者,您可以创建一个值转换器:
export class TypeColourValueConverter {
toView(value) {
let colour = value;
if (value === undefined) {
colour = red;
};
return colour;
}
}
然后你可以这样使用:
<div repeat.for="item of projects" class="col-lg-6">
<div class="card-header">
<!-- I want to change the css class red based on the value of the JSON attribute type -->
<div class.bind='item.type | TypeColour'>
...
</div>
</div>