简体   繁体   中英

NgClass of child component not triggered

I have a component for a gallery carousel with navigation for the images below it. Clicking on an image in the navigation bellow should change the image displayed on the carousel to the one selected (this works) and add a border around the selected image in the navigation (this does not). I've tried to add the border by appending a style class to the HTML element through ngClass. I keep track of the index of the selected image and when rendering the images in the navigation if the index of the selected image is the same as the index of the rendered image the border is then added. However, I assume that the elements are not rerendered because after I click on an image the border is removed from the previous image and it is not added to the new one as it should. Also, clicking on the same image after a second time adds the border (I think that this is when the child component renders once again). What is the issue here that the ngClass is ignored the first time?

HTML of image navigation:

<div *ngIf="showImageList" class="product_gallery_images mobile_hidden">
  <div *ngFor="let img of imgList; index as index" class="product_gallery_image". 
(click)="selectImage(index)">
    <img [ngClass]="{'selected_image': selectedImage === index}"  src=". 
{{img.fields.file.url}}" [id]="index.toString()">
  </div>
</div>

selectImage function:

selectImage(index) {
console.log(document.getElementById(this.selectedImage.toString()).classList);
document.getElementById(index.toString()).classList.add('selected_image');
document.getElementById(this.selectedImage.toString()).classList.remove('selected_image');
this.selectedImage = index;
this.changeImage.changeImage(index.toString());
}

I have tried to directly add and remove the class from the classList of the element but this did not work as well. I have similar functionality of the same page where the border is rendered without any issues and without the need to dynamically altering the classlist. The difference here is that this is not in a child component.

First click on the fourth image in navigation:

在此处输入图像描述

A second click on the fourth image in navigation:

在此处输入图像描述

I think the let keyword is missing:

*ngFor="let img of imgList; let index = index"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM