【问题标题】:Angular 2 trigger file upload in parent componentAngular 2在父组件中触发文件上传
【发布时间】:2016-10-14 13:21:49
【问题描述】:

我想在路由器父组件中触发文件上传。它应该调用父级中存在的两个函数openFileSelectuploadSelectedFile 来控制<input type="file"> 元素。

我的路由器是这样的:

{ 
    path: '', 
    component: HomeComponent,
    canActivate: [AuthService],
    children: [
        {
            path: '',
            redirectTo: '/dashboard',
            pathMatch: 'full'
        },
        {
            path: 'dashboard',
            component: DashboardComponent
        },
        {
            path: 'upload',
            component: UploadComponent
        }
    ]
}

文件输入在HomeComponent.html模板和子组件展示的router-outlet中:

<div class="container">
    <input type="file" (change)="fileChangeEvent($event)" #fileUpload>
    <router-outlet></router-outlet>
</div>

然后在 HomeComponent.ts 我有:

import { Component } from "@angular/core";

@Component({
    templateUrl: "home.component.html",
})
export class HomeComponent {

    filesToUpload: Array<File>;

    constructor() {
        this.filesToUpload = [];
    }

    openFileSelect() {
        // TODO - How to programmatically trigger click event on <input type="file"> ?
    }

    uploadSelectedFile() {
        this.makeFileRequest("http://localhost:3000/upload", [], this.filesToUpload).then((result) => {
             console.log(result);
        }, (error) => {
             console.error(error);
        });
    }

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        ... XHR request ...
    }
}

最后我想从 UploadComponent 内部的 HomeComponent 触发相同的 openFileSelect 方法

import { Component } from "@angular/core";

@Component({
    templateUrl: "upload.component.html",
})
export class UploadComponent {

    constructor() { }

    openFileSelectInHomeComponent() {
        // TODO - how to call HomeComponent.openFileSelect() ?
    }
}

所以我有两个问题:

  • 如何以编程方式触发点击事件?

  • 以及如何从子组件调用函数到路由父组件?

【问题讨论】:

    标签: javascript angular angular2-routing


    【解决方案1】:

    您的问题在这里有类似的答案: jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox?

    也许它会给你一个想法。或者你可以使用一个 UI 控件,比如 primeNg 的 FileUpload 控件。

    【讨论】:

    • 我已经实现了,如果我点击一个按钮来触发文件上传点击事件,但这不是我的目标。我想通过调用一个函数来触发它,例如当用户输入所有数据时它会触发文件输入对话框。我实现这一点的方法是使用提到的#fileUpload 参考变量。我的问题是我不知道如何将事件发送到组件函数内的该变量。它应该以某种方式与@ViewChild 装饰器一起使用,但我没有成功。
    猜你喜欢
    • 2018-04-30
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2016-11-27
    • 2018-12-24
    • 2017-08-04
    相关资源
    最近更新 更多