仅显示 class 用于单击的项目 angular 2

show class for only clicked item angular 2

我不知道如何为部分组件中的点击项设置可见 class。所以,我的模板是:

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

在组件中我初始化了它们..

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

然后在下一个模板中让他调用 "add-photo-component" 我想使用这个 class 我接下来要声明:

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

然后在组件 add-photo-component 中,我想在点击的图像上设置隐藏 class

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

样式:

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

那么我怎样才能只对一个选定的项目应用 class。我知道我需要以某种方式从主模板中获取索引,但我不知道如何实现这一点。

你的post乱七八糟,不知道哪个代码属于哪个组件。但是根据所选元素添加 class 很简单,而且看起来总是相似的。试试这样:

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

您可以在来自 Angular 位创作者的 official tutorial 中找到相同的示例代码。 在章节中搜索:设置所选英雄的样式

它在 angular 中非常酷 2. 这样做的想法是创建并初始化一个数组。单击 div 时,div 的索引应被推入初始化数组。并将这个 class 添加到只满足条件的 div

用于获取索引。

<div class="photo-container" *ngFor ="let i of modalImages; let index = index"></div>

用于添加CSSClass

   <div [class.ImageContainer]="array[i]=i">
       <i class="ionicons ion-ios-close remove-icon" (click)="deleteImageEvent(index)"></i>
       <img (click)="onImageClickEvent(index)" src="{{ i.thumb }}">
   </div>

(ImageContainer 是 class 名称,array[i]=i 是条件)

https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html 前往 link 了解更多详情