physicsboy
physicsboy

Reputation: 6326

Apply hover over all list items, except one that is specified

In Angular 2+, is there any way of stopping the hover CSS function on an item of a list, as specified by the Angular code?

I have a stackblitz here to show a simple example what I am talking about.

I am using the ngClass feature to apply style dynamically to whichever list item is selected at the time, as this will change (only one item will be selected at any one time).

<ul>
  <li id="{{item.name}}" *ngFor="let item of list" [ngClass]="{disableThis: item.selected}">{{item.name}}</li>
</ul>

I have looked into the :not() feature of CSS application, however I could not find a way of getting this to work with data interpolation.

ie:

.myElement:hover:not({{listItem.name}}) {
  background: green;
  color: white;
} 

Upvotes: 2

Views: 1078

Answers (3)

user7027429
user7027429

Reputation:

app.component.ts

  items = {
    name: 'name',
    lang: ['php', 'javascript', 'angular']
  };

app.component.html

<ul>
 <li id="{{item.name}}" class="items" *ngFor="let item of items.lang">{{item}}</li>
</ul>

app.component.css or app.component.scss

// 1
.items:not(:first-of-type):hover {
  color: red;
}

// 2
.items:not(:last-of-type):hover {
  color: red;
}

// 3
.items:not(:first-child):hover {
  color: red;
}

// 4
.items:not(:last-child):hover {
  color: red;
}

// 5 by index of item
.items:not(:nth-child(2)):hover {
  color: red;
}

// 6 by index of item
.items:not(:nth-child(3)):hover {
  color: red;
}

By selector Id


app.component.ts

items = [
    {
      id: 'php',
      lang: 'php'
    },
    {
      id: 'angular',
      lang: 'angular'
    },
    {
      id: 'css',
      lang: 'css'
    }
  ];

app.component.html

<ul>
    <li id="{{ item.id }}" class="items" *ngFor="let item of items">{{item.lang}}</li>
</ul>

app.component.css or app.component.scss

.items:not(#angular):hover {
  color: red;
}

// Or
.items:not(#php):hover {
  color: red;
}

// Or
.items:not(#css):hover {
  color: red;
}

Upvotes: 1

physicsboy
physicsboy

Reputation: 6326

@Tushar won the day with a quick comment to say:

The selector should be .myElement:not(.disableThis):hover {. Assuming that myElement class is applied to all li elements.

This worked for me and also in my larger project that I was extracting the code from.

Upvotes: 0

DorotkaMakotka
DorotkaMakotka

Reputation: 26

If stopping hover depends on particular element having class disableThis attached, you only have to modify your css like this:

.disableThis,
.disableThis:hover {
  background: grey;
  color: white;
}

Upvotes: 0

Related Questions