How do I put a class to work in front of a condition using ngclass

Asked

Viewed 50 times

1

I’m writing an angular code and I’m trying to make a situation where, by choosing the name of a city, depending on its size, the size of the space that bears the name increases depending on the name of the city. I tried to make a class in css that only activates when the condition happens but keeps giving error and I don’t know why. Here’s the angular snippet:

<div [ngClass]="{city.length < 16 ? 'desktopCityFilterName' : 'desktopCityFilterName2'}">{{city}}

Here the css:

.desktopCityFilterName {
  padding-right: 0px;
  padding-left: 15px;
  width: 115px;
}

.desktopCityFilterName2 {
  padding-right: 0px;
  padding-left: 15px;
  width: 189px;
}

In case I was clear, the user chooses a city and the display increases the size of the space in which the name is written if the city name exceeds 16 characters.

Ex: Aracajú less than 16, thus width continues 115px

Jordan Fields more than 16, so width becomes 189px

1 answer

2


Your problem there is that the directive ngClass, doesn’t work that way as a ngIf for example, that a condition may be passed ternária, this directive works differently.

For what you want to do, which is to set a class in the div according to the size of the string, the correct way (I don’t know if the only way) is to declare the class and then pass the condition after the symbol : separating the classes by a sign of , and inserting the other class with the other condition:

<div [ngClass]="{'desktopCityFilterName': city.length < 16, 'desktopCityFilterName2': city.length > 16}"> {{city}} </div>

You can see an example working here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.