【问题标题】:Angular2+ File Upload with ng2-file-upload - Child component keeps calling Parent Component functionsAngular2+ 使用 ng2-file-upload 上传文件 - 子组件不断调用父组件函数
【发布时间】:2019-01-17 15:38:57
【问题描述】:

我有一个父组件,其中有 2 个输入 type="file" 元素,它们在文件更改时调用函数 getFileForParent()

<input type="file" (change)="getFileForParent()" />

在我的子组件中,我有一个:

<input type="file" (change)="getFileForChild()" />

但是每当我在子组件上选择一个文件时,父母getFileForParent 就会被调用。 我正在使用ng2-file-upload

父 ts:

getFileForParent(){
    if(this.uploaderForParent.queue[0].file.type != 'application/PDF'){
        this.showError("Please select pdf files only");
        return;
    }
    this.uploaderForParent.uploadAll();
}

儿童 ts:

getFileForChild(){
    if(this.uploaderForChild.queue[0].file.type != 'application/PDF'){
        this.showError("Please select pdf files only");
        return;
    }
    this.uploaderForChild.uploadAll();
}

【问题讨论】:

  • 可以分享一下你的ts代码吗
  • @Chellappan 完成。

标签: javascript html angular file-upload ng2-file-upload


【解决方案1】:

它对我来说很好用

DEMO

parent.component.html

<h1>
    Parent Component File inputs:
</h1>

<input type="file" ng2FileSelect [uploader]="uploaderForParent" (change)="getFileForParent()" />
<input type="file" ng2FileSelect [uploader]="uploaderForParent" (change)="getFileForParent()" />


<h1>
    Child Component File inputs:
</h1>

<app-child-comopnent></app-child-comopnent>

parent.component.ts:

uploaderForParent: FileUploader = new FileUploader({ url: 'any' });

  getFileForParent() {
    console.log("Parent");
    console.log(this.uploaderForParent);


    if (this.uploaderForParent.queue[0].file.type != 'application/PDF') {
      alert("Please select pdf files only");
      return;
    }
    //this.uploaderForParent.uploadAll();
  }

child.component.html:

<input type="file" ng2FileSelect [uploader]="uploaderForChild" (change)="getFileForChild()" />

child.component.ts:

uploaderForChild: FileUploader = new FileUploader({ url: 'any' });

getFileForChild() {

    console.log("child");
    console.log(this.uploaderForChild);
    if (this.uploaderForChild.queue[0].file.type != 'application/PDF') {
      alert("Please select pdf files only");
    }
    //this.uploaderForChild.uploadAll();
  }

【讨论】:

    猜你喜欢
    • 2016-09-18
    • 2020-01-07
    • 2018-05-20
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多