如何在Angular中使用* ngFor和* ngIf?

时间:2018-12-12 12:15:09

标签: angular

这里有3个div,它们是用*ngFor渲染的,divimageimageNameimagesize

imageName扩展名错误(请参阅第三个div)或没有扩展名(请参阅第一个)时,我想禁用按钮的dblclick。我该怎么办?

enter image description here

<div>
 <mat-card *ngFor="let imagespayload of uploadedImagesObj" (click)="activeFolder=imagespayload"
  (dblclick)="previewFiles(imagespayload.folderid,imagespayload.imageName,imagespayload.urloffolder)"
  (contextmenu)="onRightClick($event,imagespayload)">

  <div *ngIf="getExstendsionIfNotExtension(imagespayload.imageName);else noExtension">
    <img [src]="http://localhost:3000/{{imagespayload.urloffolder}}/{{imagespayload.imageName}}" style="height:40px;width:40px">
    <h3>{{imagespayload.imageName}}</h3>
    <h4>{{imagespayload.imagesize}}</h4>
  </div>

  <ng-template>
    <h5>No Extension of File..</h5>
  </ng-template>
 </mat-card>
</div>
public getExstendsionIfNotExtension(image) {
  if(image.endsWith('jpg') || image.endsWith('jpeg') || image.endsWith('gif') || image.endsWith('png') || 
    image.endsWith('tiff') || image.endsWith('tif') || image.endsWith('pdf')) {
     return true;
  }
}

3 个答案:

答案 0 :(得分:3)

我个人会处理事件是否实际上在事件处理程序本身中执行了任何操作。因此,我将编写以下内容:

<div>
  <mat-card *ngFor="let imagespayload of uploadedImagesObj"
    (dblclick)="preview(imagespayload.folderid, imagespayload.imageName, imagespayload.urloffolder)">

    <div *ngIf="hasPreviewableExtension(imagespayload.imageName);else noExtension">
    </div>
  </mat-card>
</div>
public preview(folderid, fileName, urloffolder) {
  if(!this.hasPreviewableExtension(fileName) {
    return;
  }

  // Your code here.
}

public hasPreviewableExtension(fileName) {
  const suffixes = ['jpg', 'jpeg', 'gif', 'png', 'tiff', 'tif', 'pdf'];
  return suffixes.some(suffix => fileName.endsWith(suffix));
}

请注意,我确实做了一些更改,因为这不仅与图像有关,而且与PDF文件有关。

答案 1 :(得分:0)

在您的TS文件中:

public getExstendsionIfNotExtension(image) {
  return image.endsWith('jpg') || image.endsWith('jpeg') || image.endsWith('gif') || image.endsWith('png') || 
    image.endsWith('tiff') || image.endsWith('tif') || image.endsWith('pdf')
}

在您的模板文件中:

<div>
 <mat-card *ngFor="let imagespayload of uploadedImagesObj" (click)="activeFolder=imagespayload"
  (dblclick)="previewFiles(imagespayload.folderid,imagespayload.imageName,imagespayload.urloffolder)"
  (contextmenu)="onRightClick($event,imagespayload)">

  <div *ngIf="getExstendsionIfNotExtension(imagespayload.imageName)">
    <img [src]="http://localhost:3000/{{imagespayload.urloffolder}}/{{imagespayload.imageName}}" style="height:40px;width:40px">
    <h3>{{imagespayload.imageName}}</h3>
    <h4>{{imagespayload.imagesize}}</h4>
  </div>

  <ng-template *ngIf="!getExstendsionIfNotExtension(imagespayload.imageName)">
    <h5>No Extension of File..</h5>
  </ng-template>
 </mat-card>
</div>

答案 2 :(得分:0)

在垫板上使用disable属性而不是*ngIf

[disabled]="!getExstendsionIfNotExtension(imagespayload.imageName)'