如何在ngFor循环中获得点击的项目?

时间:2018-07-12 08:32:49

标签: angular

在ngFor中的<a></a> html元素上如何触发点击事件。我想为每个货运附件下载文件。我希望下面的代码足以说明问题。 代码:

attachments.component.ts

export class ShipmentDetailsAttachmentsComponent implements OnInit {

  @Input("shipment")
  public _shipment: Shipment;

  constructor(private _shipmentService: ShipmentService) {}

  ngOnInit() {}

  public getAttachment(shipmentId: number, attachmentId: number) {

    this._shipmentService.getShipmentAttachment(shipmentId, attachmentId).subscribe((content: Blob) =>
    {
      // file is transfered Ok, I get blob content
      let url = window.URL.createObjectURL(content);
      let link = this.clickedHtmlAelement; // here I want to get the clicked HTML element
      link.href = url;
      link.download = 'fileName';
      link.click();

      window.URL.revokeObjectURL(url);

    }, (error: MessageModel) => { 
      console.log("failed to retrieve attachment content");
  });
}

attachments.component.html

<div *ngFor="let attachment of _shipment.attachments">
  <a (click)="getAttachment(_shipment.id, attachment.id)">{{attachment.name}}</a>
</div>

如果我即时创建<a>元素,它可以工作,但我相信有更好的解决方案:

  let url = window.URL.createObjectURL(content);      
  var a = document.createElement('a');
  document.body.appendChild(a);
  a.setAttribute('style', 'display: none');
  a.href = url;
  a.download = "file";
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove(); // remove the element*/

如果有人感兴趣->用于下载文件的工作代码:

打字稿

let url: string = this.getFullUrl(`/api/v1/shipments/${shipmentId}/attachments/${attachmentId}`);
let headers: HttpHeaders = new HttpHeaders().set('Authorization', this.token);

return this._httpClient.get(url, {
  headers: headers,
  responseType: 'blob' // this is very important, ajax setting responseType
})
.pipe(
  catchError(this.handleError)
);

1 个答案:

答案 0 :(得分:0)

您可以使用file-saver

  import * as FileSaver from 'file-saver';

  this._shipmentService.getShipmentAttachment(shipmentId, attachmentId)
    .subscribe(data => {
      FileSaver.saveAs(data.content, data.fileName);
    },
    error => {
      console.error('Download Error', error);
    },
    () => console.log('Completed'));

并在服务中:

this.http.post(`/my/download`,
            data, 
            {responseType: 'blob', observe: 'response'})
          .map( res => ({content: res.body, 
                         fileName: res.headers.get('content-filename')}));