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

javascript - ngClass condition is not working on multiple conditions - Stack Overflow

programmeradmin5浏览0评论

I am trying to implement [ngClass] based on different conditions here is my

condition
 [ngClass]="{'validator':lang.VideoURL!=null, 'labeltitle': lang.VideoURL==null}"

but when value of lang.VideoURL is null then labeltitle class is not applying on the page and by default validator class is applying when value of lang.VideoURL is null

I am trying to implement [ngClass] based on different conditions here is my

condition
 [ngClass]="{'validator':lang.VideoURL!=null, 'labeltitle': lang.VideoURL==null}"

but when value of lang.VideoURL is null then labeltitle class is not applying on the page and by default validator class is applying when value of lang.VideoURL is null

Share Improve this question asked May 9, 2019 at 12:49 Gaurav_0093Gaurav_0093 1,0307 gold badges30 silver badges58 bronze badges 2
  • 2 try this: [ngClass]="{'validator':lang.VideoURL, 'labeltitle': !lang.VideoURL}" – Radonirina Maminiaina Commented May 9, 2019 at 12:51
  • FYI my guess is that your logic in the condition is actually fine, but that your value of lang.VideoURL is not null but is probably undefined, which would cause the behavior you are explaining above. This is also why the suggested answers are working, since they are not concerned with null or undefined, and are instead focused on false or true (both null and undefined will be considered false, so either works then) – ccamac Commented May 9, 2019 at 13:10
Add a ment  | 

4 Answers 4

Reset to default 4

Try:

[ngClass]="lang.VideoURL ? 'validator' : 'labeltitle'"

@porgo's answer is also correct but if you have more condition to check you can try like this.

[ngClass]="[lang.VideoURL != null: 'validator', lang.VideoURL == null: 'labeltitle']"

Another option is class property binding shown here https://angular.io/guide/template-syntax#binding-targets. This is helpful if you have more than one class that could be valid at a time but which are all conditional.

[class.validator]="lang.VideoURL" [class.labeltitle]="!lang.VideoURL"

this is the way to use ngClass multi-condition.

 [ngClass]="{'first-class': condition1,'second-class': condition2}"
发布评论

评论列表(0)

  1. 暂无评论