How to give an element a class in Angular 4

I was experimenting with Angular 4 to create an image gallery. The idea is to assign a CSS class to the clicked image, which will display a red border around it. Below is the CSS stylesheet for this image gallery.

When I click on an image, I want a red selection square to appear around it. The 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;
}

Here 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>

Below is the component code:

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';
  }
}

Answer №1

Utilize the [ngClass] attribute to dynamically assign classes based on the id.

Within your HTML document:

<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>

Incorporated in your TypeScript script:

addClass(id: any) {
    this.id = id;
}

Answer №2

Take a look at this interactive example showcasing how the ngClass directive can be utilized.

In this demonstration, I am using div elements instead of img elements.

Example 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>

TypeScript Code:

export class App {
  selectedIndex = -1;

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

Answer №3

In order to apply a specific class, consider utilizing TypeScript to create a function that evaluates when the desired class should be added.

Sample TypeScript Function

function displayElement():boolean{
    if (/* Your conditions here */)
        return true;
}

Corresponding CSS Style:

.element-hidden {
    visibility: hidden;
}

HTML Implementation:

<span [class.element-hidden]="displayElement()"></span>

Answer №4

For individual toggles on each div without affecting others, follow these steps:

This is the method I used to resolve the issue...

<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>

Although it involves assigning custom numbers, it does the job effectively.

Answer №5

2030 solution:

Utilize renderer2:

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

constructor(private utility: Renderer2) { }

Next, provide the element reference where the new style will be applied along with the style name:

this.utility.addClass(this.myDiv.nativeElement, 'highlighted');

Answer №6

You have the capability to achieve this effect without the need for any JavaScript, simply utilizing CSS.

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

If you wish to apply a different CSS class upon clicking, you can utilize query selectors like so:

<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 the controller, search for any image with a red border and remove it. Then, by passing the image ID, add the border class to that specific image.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can anyone help me with coloring Devanagiri diacritics in ReactJS?

I am currently working on a ReactJS project and I have come across an issue. I would like for the diacritic of a Devanagiri letter to be displayed in a different color than the letter it is attached to. For example: क + ी make की I was wondering ...

Changing the absolute layout to utilize floats

I am seeking guidance on a project I am currently working on and would greatly appreciate any help. Main Goal: The objective is to create a drag and drop CMS that allows users to draw elements on a grid and rearrange them as needed. The system will recor ...

Please place the accurate image inside the designated box based on the corresponding ID number

I am currently working on a function that retrieves image data from a database and displays it in HTML using *ngFor directive. In order to display the correct image, I need to fetch the ID associated with the image data and use it to retrieve the correspo ...

Chrome browser alignment problems

Here are the lines in my code: <TD id=“avail_1” style=“display:none;availability:hidden”>UrgentAvail</TD> <TD id=“avail1_1” style=“display:none;availability:hidden”>substitutedBy</TD> When I test the application o ...

Aligning adaptable content using css

Currently, I am facing a challenge in centering an (inline?) element horizontally within my container div. My goal is to have "some text" with a background that retracts to it, and to achieve this while keeping everything centered within the containing ele ...

Unexpected behavior with the ion-datetime time picker on an Android device

I am encountering challenges with a Date and Time entry feature in my Angular/Ionic application that involves date pickers. When I tap on the Time field, the time picker opens. Everything works perfectly in my browser - I can select a time, spin the value ...

In the mobile view of the jumbotron, there is a noticeable blank area on the right side

I've searched high and low for a solution to this issue, but nothing seems to pinpoint the cause of the problem. The white space that's causing trouble is evident in the following image: https://i.sstatic.net/95Rh6.jpg Could you help me identif ...

Having issues with Tailwind classes not being applied properly on dynamically generated pages in Gatsby-node

Currently, I am working on building dynamic pages using gatsby-node. The templates for these pages are stored in the templates/ directory. However, I have run into an issue where I cannot utilize tailwind classes within these templates unless they are al ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...

Why does my <p> element in Bootstrap continue to elongate and push everything below it down when I minimize the window?

I've got a standard bootstrap layout set up. <div classs="row-fluid"> <div class="span12" style="background:black; padding:25px 0px;">content content</div> </div> <div class="span4 offset2"> <p>blah blah bl ...

Adjust the transparency of a separate image within a different container by hovering over another image container

Is my goal too complex to achieve? I am attempting to create a hover effect where the opacity of artwork1 and button1 changes simultaneously when hovered over. However, I am having trouble properly labeling my elements and getting them to interact as inten ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

Presenting SQL information in a hierarchical Angular grid for easy visualization

As a newcomer to Angular, I have a requirement to display data in a multilevel/hierarchical Angular Grid. The data is retrieved from a SQL Database using a query with arguments provided in the where clause. Some questions that come to mind are: Is there ...

Angular 2: Implementing functionality on selected option

I have written code for my HTML <select [(ngModel)]="empfile.storeno" class="form-control"> <option *ngFor="let p of concept" [ngValue]="p.MAP_Code">{{p.MAP_Code}}</option> </select> As for my component public concept = []; ...

Encountering an "Invalid parameter: redirect_uri" error in Keycloak while manually refreshing the page

This is an Angular 17 single-page application utilizing the latest version of keycloak-angular (15.2.1 at the time of writing). I'm facing a perplexing issue where after successfully authenticating and logging out, if I reload the page, it breaks enti ...

The hierarchy of styles in Rails CSS/SCSS

I'm currently exploring the concept of css precedence rules in rails. In my application, I am looking to apply different css rules based on different controllers. However, when I add css to one of the css.scss files, it ends up affecting all controll ...

Adding a 'dot' to the progress bar in Bootstrap enhances its visual appeal

I am currently working on a progress bar and I would like it to look similar to this: https://i.sstatic.net/TSDEy.png However, my current output looks like this: https://i.sstatic.net/rQhYc.png I'm puzzled as to why the tooltip is floating there, ...

Adding a border to dynamically generated content while excluding the outer borders using CSS - an easy guide

My current project involves establishing a grid system that dynamically populates content, resulting in an uncertain number of elements being created. At the moment, each element is placed within a flexbox container with 3 elements per row. If there are mo ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...