45

I was trying to create an image gallery with Angular 4.The logic behind this is to add a Cascading Style Sheet (CSS) class to the selected image that will show a red border on the selected (clicked) image. This is the CSS stylesheet for an image gallery.

I want to show a red selection square on the image I have clicked. this-is-a-class should be added to the selected image.

#container{
  border:1px solid red;
  height:auto;
}

ul li{
  margin-right:20px;
  margin-left:0;
  list-style-type:none;
  display:inline;
}

ul li img{
  width: 200px;
  height:200px;
  border:1px solid grey;
}

#select{
  border:2px solid violet;
}

.this-is-a-class{
  border: 10px solid red !important;
}

following is the template code

<div id="container">
  <ul>
    <li><img class="this-is-a-class" id="1" src="../../assets/images/1.jpg" (click)="addClass(id=1)"/></li>
    <li><img id="select" src="../../assets/images/2.png" (click)="addClass(id=2)"/></li>
    <li><img id="3" src="../../assets/images/3.jpg" (click)="addClass(id=3)"/></li>
    <li><img id="4" src="../../assets/images/4.png" (click)="addClass(id=4)"/></li>
    <li><img id="5" src="../../assets/images/5.jpg" (click)="addClass(id=5)"/></li>
  </ul>
</div>

<div>
  <h1>You Clicked on: {{id}}</h1>
</div>

The component code is as follows

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})

export class UserComponent implements OnInit {
  id: number;
  constructor() {
    console.log("Constructor working..")

  }

  ngOnInit() {
    console.log('ngOnInit works..');
  }

  //function to add the class to selected image to show the border.
  addClass(id) {
    this.id = id;
    //id = this.id? 'selectedImg' : 'null';
  }
}
4
  • is the css working fine if you assign it to li manually ? Commented Aug 22, 2017 at 11:24
  • It is working fine. Commented Aug 22, 2017 at 11:26
  • 1
    Please read Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. Commented Aug 22, 2017 at 11:32
  • How would you do this if you were using ngFor and don't have specific ids for each element? Commented Jan 12, 2023 at 17:23

6 Answers 6

88

Use [ngClass] and conditionally apply class based on the id.

In your HTML file:

<li>
    <img [ngClass]="{'this-is-a-class': id === 1 }" id="1"  
         src="../../assets/images/1.jpg" (click)="addClass(id=1)"/>
</li>
<li>
    <img [ngClass]="{'this-is-a-class': id === 2 }" id="2"  
         src="../../assets/images/2.png" (click)="addClass(id=2)"/>
</li>

In your TypeScript file:

addClass(id: any) {
    this.id = id;
}
Sign up to request clarification or add additional context in comments.

4 Comments

i want to add the class dynamically to the element when i click on it.
and that why im using ngClass
Can we also remove the class we added?
How would you do this if you were using ngFor and don't have specific ids for each element?
10

Here is a plunker showing how you can use it with the ngClass directive.

I'm demonstrating with divs instead of imgs though.

Template:

<ul>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>

TS:

export class App {
  selectedIndex = -1;

  setSelected(id: number) {
    this.selectedIndex = id;
  }
}

Comments

7

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

1 Comment

This is the least disruptive option (tho not always feasible.) Even as of Angular 8, you can get into situations where ngClass results will override what someone else has done, rather than giving you a pure union. I think typically when one or more directives use ngClass in addition.
0

If you need that each div will have its own toggle and don't want clicks to affect other divs, do this:

Here's what I did to solve this...

<div [ngClass]="{'teaser': !teaser_1 }" (click)="teaser_1=!teaser_1">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_2 }" (click)="teaser_2=!teaser_2">
...content...
</div>

<div [ngClass]="{'teaser': !teaser_3 }" (click)="teaser_3=!teaser_3">
...content...
</div>

it requires custom numbering which sucks, but it works.

Comments

0

2024 answer:

Inject renderer2:

import { Renderer2 } from '@angular/core';

constructor(private renderer: Renderer2) { }

Then pass in the element reference the new class will be added to and the class name:

this.renderer.addClass(this.myButton.nativeElement, 'copied');

Comments

-5

you can try this without any java script you can do that just by using CSS

img:active,
img:focus,
img:hover{ 
border: 10px solid red !important
}

of if your case is to add any other css class by clicking you can use query selector like

<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >

in controller first search for any image with red border and remove it then by passing the image id add the border class to that image

$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}

4 Comments

angular 4 - $scope?
oops! i thought angularjs anyhow u can use the logic
check out ngClass as it's an infinitely better answer than this. also you shouldnt use !important by default
This is angular.js, not angular

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.