在Angular 6中,你可以使用ngClass指令和条件表达式来应用对象数组样式。下面是一个示例:
在组件的HTML模板中,你可以使用ngClass指令将条件样式应用于文本区域:
{{ item.text }}
在组件的TypeScript文件中,你可以定义isHighlighted和isBold方法来确定对象数组中的每个项是否应该应用样式:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent {
items = [
{ text: 'Item 1', highlight: true, bold: false },
{ text: 'Item 2', highlight: false, bold: true },
{ text: 'Item 3', highlight: true, bold: true }
];
isHighlighted(item: any) {
return item.highlight;
}
isBold(item: any) {
return item.bold;
}
}
在上面的示例中,我们定义了一个items数组,其中包含三个对象。根据每个对象的highlight和bold属性,我们决定是否应用highlight和bold样式。
请确保在组件的样式文件中定义了.highlight和.bold类:
.highlight {
background-color: yellow;
}
.bold {
font-weight: bold;
}
这样,当Angular渲染组件时,文本区域中的每个项都将根据条件应用适当的样式。
上一篇:Angular 6中的条件语句