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
4 Answers
Reset to default 4Try:
[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}"