Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine [NgStyle] With Condition (if..else)

People also ask

Can we use NgClass and NgStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What type of directive is NgStyle?

NgStylelinkAn attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional .


One can also use this kind of condition:

<div [ngStyle]="myBooleanVar && {'color': 'red'}"></div>

It requires a bit less string concatenation...


Using a ternary operator inside the ngStyle binding will function as an if/else condition.

<div [ngStyle]="{'background-image': 'url(' + value ? image : otherImage + ')'}"></div>

The previous answers did not work for me, so I decided to improve this.

You should work with url(''), and not with value.

<li *ngFor="let item of items">
  <div
    class="img-wrapper"
    [ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
  </div>
</li>

You can use this as follows:

<div [style.background-image]="value ? 'url(' + imgLink + ')' : 'url(' + defaultLink + ')'"></div>

To add and simplify Günter Zöchbauer's the example incase using (if...else) to set something else than background image :

<p [ngStyle]="value == 10 && { 'font-weight': 'bold' }">

<h2 [ngStyle]="serverStatus == 'Offline'? {'color': 'red'{'color':'green'}">Server with ID: {{serverId}} is {{getServerStatus()}} </h2>

or you can also use something like this:

<h2 [ngStyle]="{backgroundColor: getColor()}">Server with ID: {{serverId}} is {{getServerStatus()}}</h2>

and in the *.ts

getColor(){return this.serverStatus === 'Offline' ? 'red' : 'green';}

I have used the below code in my existing project

<div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
</div>