最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular2 [ngClass] - Combining direct binding with conditional classes - Stack Overflow

programmeradmin2浏览0评论

I currently have two different working implementations of [ngClass] on an element;

[ngClass]="{ selected: element.isSelected, highlighted: element.isHighlighted}"

and

[ngClass]="element.customClasses"

Is it possible to bine both of these approaches in the template, or do I have to create a method in my ponent to return an array of classes based on the logic above?

Thanks!

I currently have two different working implementations of [ngClass] on an element;

[ngClass]="{ selected: element.isSelected, highlighted: element.isHighlighted}"

and

[ngClass]="element.customClasses"

Is it possible to bine both of these approaches in the template, or do I have to create a method in my ponent to return an array of classes based on the logic above?

Thanks!

Share Improve this question asked Feb 12, 2017 at 18:28 Chris BrownChris Brown 4,6553 gold badges31 silver badges37 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

I opted for using [class.*] to set the conditional classes, leaving [ngClass] to handle the binding;

<div 
  [ngClass]="element.customClasses" 
  [class.selected]="element.isSelected"
  [class.highlighted]="element.isHighlighted"
></div>

You can directly set the customClasses to your template as

<span class="customClasses">something</span>

And also you can use [ngClass] which will append your classes based on the condition, so putting together

<span [ngClass]="{ selected: element.isSelected, 
                 highlighted: element.isHighlighted}" 
                 class="customClasses">something
</span>
发布评论

评论列表(0)

  1. 暂无评论