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 t
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;
}
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.
Here is a plunker showing how you can use it with the ngClass
directive.
I'm demonstrating with div
s instead of img
s 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;
}
}
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');
}
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>