Search code examples
htmlcssangulartypescriptng-class

show class for only clicked item angular 2


I don't know how to set visible class only for clicked item in partial component. So, I've temaplate with:

<div class="photo-container" *ngFor ="let i of modalImages; let index = index">
       <div [ngClass]="ImageContainer">
           <i class="ionicons ion-ios-close remove-icon" (click)="deleteImageEvent(index)"></i>
           <img (click)="onImageClickEvent(index)" src="{{ i.thumb }}">
       </div>
</div>

In component I'm initialised them..

export class ImageModal implements OnInit, AfterViewInit {
    @ViewChild('reviewFileInput') reviewFileInput: ElementRef;
    @Input('modalImages') public modalImages: any;
    @Input('imagePointer') public imagePointer: number;
    @Output('cancelEvent') cancelEvent = new EventEmitter<any>();
    @Input('imageClass') public imageClass: any;
    ...

Then in that next template let him call "add-photo-component" which I want to use this class i'm declaring next:

<ImageModal #imageModal
                       [modalImages]="images"
                       [isReviewPhotos]="true"
                       [imageClass]="classMap"
                       (cancelEvent)="cancelImageModel()"
                       [options]="options"
                       [isUploadButtonAvailable]="isUploadButtonAvailable"
                       (clickEvent)="onUploadClick()"
                       (handleEvent)="handleNgUpload($event)"
                       (deleteEvent)="deleteImage($event)"
                       (handleSelectedImgEvenet)="onImageClick($event)"
                       (imageContainer)="{'img-media-container': isImageSelected}"> // And this class which I want to use 
</ImageModal>

then in component add-photo-component I want to set this hided class on clicked image

onImageClick($event) {
        if ($event && $event.index >= 0) {
            this.selectedImage = this.images[$event.index];
            this.isImageSelected = !this.isImageSelected;
        }
    }

styles:

.img-media-container{
    border-radius: 10px;
    border: 3px solid #4774c5;
    padding: 3px;
}

So how can I apply class only on one selected item. I know that somehow I need to take an index from main template, but I dont have any ideas how I can realized that.


Solution

  • Your post is messy and I dont know which code belong to which component. But add class depending on selected element is simple and always look similarly. Try in this way:

    <div *ngFor ="let image of modalImages; let index = index">
           <div [class.img-media-container]="image === selectedImage" >
              <!-- some code -->
           </div>
    </div>
    

    You can find the same example code in official tutorial from Angular creators. Search in chapter: Style the selected hero