角度:动态指令注入不起作用

时间:2020-03-21 19:14:50

标签: angular

我试图将ng2-file-upload添加为自定义指令,而没有在多个地方填充选项,所以我决定有一个指令可以为我做,我将根据不同的情况使用它。我无法完成这项工作。

Stackblitz:https://stackblitz.com/edit/angular-jopscg

这就是我打算打电话的方式

<div>
  Attachments
  <input type="file" appAttachments [proxy]="proxy" name="fileInput" multiple #fileInput />
  <div>
    <mat-icon #proxy>attachment</mat-icon>
  </div>
</div>

在指令中

import { Directive, ElementRef, HostBinding, Renderer2, Input, OnInit } from '@angular/core';
import { FileUploader, FileSelectDirective } from 'ng2-file-upload';

@Directive({
  selector: '[appAttachments]'
})
export class AttachmentsDirective implements OnInit {
  @HostBinding('attr.ng2FileSelect')
  ng2FileSelect = new FileSelectDirective(this.el);

  @HostBinding('attr.uploader')
  uploader: FileUploader = new FileUploader({
    url: `/api/upload`,
    itemAlias: 'fileInput'
  });

  @HostBinding('style.display')
  display = 'none';



  fileHtml = `<input type="file" hidden name="fileInput" ng2FileSelect [uploader]="uploader" #fileInput multiple/>`;

  @Input()
  proxy: any = null;


  constructor(
    private el: ElementRef,
    private renderer: Renderer2,
  ) {
    console.log(this.proxy)

    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
      this.uploader.uploadAll();
      console.log('hi')
    };
    this.uploader.onCompleteItem = (req: any, res: any) => {
      console.log(req, res);
    };
  }

  ngOnInit() {
    this.ng2FileSelect.uploader = this.uploader;
    this.ng2FileSelect.onChange();
    if (this.proxy) {
      this.renderer.listen(this.proxy._elementRef.nativeElement, 'click', (event) => {
        this.el.nativeElement.click();
      });
    }
  }

}

实际的想法是像这样使用它,使用结构化指令或类似方法在Dom中添加一个文件元素。

<div>
  Attachments
  <!--inject file element dynamically-->
  <div>
    <mat-icon *appAttachments>attachment</mat-icon>
  </div>
</div>

0 个答案:

没有答案