1

So im having trouble in the angular if statement, i wanna write a css line of code in case of the if statement is false. Can someone help me out?

Here is the code in the HTML file code:

<div *ngIf="city.length < 16; else BigName">{{city}}</div>
                             <ng-template #BigName>
                                .desktopCityFilterName {
                                padding-right: 0;
                                padding-left: 15px;
                                width: 205px;
                            }
                            {{city}}
                            </ng-template> 

In case i have not made myself clear, what i want to do is display the name in case its length is less than 16 characters, and in case of not, adjust the size of the container and then display it.

3 Answers 3

2

You should use ngClass. This is the syntax: [ngClass]="{'class': true}"

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

The class is only added if the length is > 16.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried what you suggested and it didn't work. You mean something like this: <div [ngClass]="{city.length < 16 ? 'desktopCityFilterName' : 'desktopCityFilterName2'}">{{city}}</div> ?
No, it should be <div [ngClass]="{'deskTopCityFilterName': city.length > 16, 'deskTopCityFilterName2': <= 16}">{{city}}</div>. First you put the class name, and then a boolean expression - if it is true, the class will be applied to the div.
1

Use [ngClass] or [ngStyle] directives to attach dynamic css. If you extract your css into class you can do sth like this:

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

Or you can execute a function which will return a list (or single) css classess. Another way is to use a [ngStyle]. You can execute a function which will return an object with your style:

getStyle = () => {backgroundColor: 'red'};

And inside Html file:

<div [ngStyle]="getStyle()">{{city}}</div>

Comments

0

To add a conditional class in Angular you can pass an object to ngClass where key is the class name and value is condition.

<div [ngClass]="{'classname' : condition}"></div>

Add a class based on multiple conditions

<div [ngClass]="{'warn': priority > 10 && priority  < 20}">
    {{text}}
</div> 

Pass a method to ngClass

<div [ngClass]="getClass(priority)">{{text}}</div>

getClass(priority){
  var classList='';
  if(priority < 10){
     classList = 'message'; 
  }else if (priority > 10 && priority < 20){
      classList = 'warn';
  }else if(priority > 30){
      classList = 'error';
  }
  return classList;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.