Reputation: 530
I am currently working on an Angular 2 webapp. In a view, the active element should get an additional CSS class when clicked. The element that is clicked, needs to get an additional CSS class.Adding the CSS attribute ":active" including an own CSS class is not working, because the class is removed when the user removes the finger from the mouse button. The CSS property ":focus" is not working at all. I tried with Angular2 directives Ng-click, ng-switch, ng-if and ng-class. The code so far -
The template:
<footer>
<div class="thumbnail-slider">
<div class="thumbnail-img-container">
<img class="thumbnail-slider-img" (click)="getActualImage(url)"
*ngFor="let url of urls" [src]="url"/>
</div>
</div>
</footer>
The component:
import { Component, NgModule, Input, Output, ViewChild, EventEmitter, ElementRef, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { BrowserModule, DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Http, Response, ResponseContentType } from '@angular/http';
ReqConstImages } from '../../services';
import { Subscription } from 'rxjs/Subscription';
import { Subject } from 'rxjs/Subject';
import { ObservableUtility } from '../../helper/index';
import { trigger, state, style, transition, animate } from '@angular/animations';
let css: any = require('!raw-loader!less-loader!./thumbnail-slider.less');
@Component({
selector: 'thumbnail-slider',
templateUrl: 'thumbnail-slider.html',
styleUrls: [css],
animations: [
trigger('click', [
state('inactive', style({
border: '5px yellow solid'
})),
state('active', style({
border: '6px green solid'
}))
])
]
})
export class ThumbnailSliderComponent implements OnInit, AfterViewInit, OnDestroy {
constructor(private http: Http, private sanitizer: DomSanitizer, private observableUtility: ObservableUtility) { };
}
This doesn´t seem to be a big deal; however, I haven´t figured out the right solution yet. The element that is clicked just needs an additional CSS class. As I am new to Angular2, any hints or help would be very much appreciated!
Upvotes: 0
Views: 1416
Reputation: 2013
You can try something like below. use a variable selectedUrl
to store the clicked URL, check if it matched the iterating image, and if so, set the class active
.
<img
class="thumbnail-slider-img"
*ngFor="let url of urls"
[src]="url"
(click)="selectedUrl=url"
[class.active]="selectedUrl === url"/>
Upvotes: 1
Reputation: 2408
Try creating a new variable in your component ts, change the value in the clicked function and finally use inside of the class attribute
like: *.ts
public changedClass = "class1";
onClickedItem(){
this.changedClass = "class2";
}
*.html (Template)
<div class="{{changedClass}}" (click)="onClickedItem()"></div>
here you have a code to change the class in the element when you click it.
Upvotes: 2