父组件中的Angular 2触发器文件上载

时间:2016-10-14 13:21:49

标签: javascript angular angular2-routing

我想在路由器父组件中触发文件上传。它应该调用父,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() ?
    }
}

所以我有两个问题:

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

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

1 个答案:

答案 0 :(得分:0)

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

也许它会给你一个想法。或者您可以使用像primeNg的FileUpload控件这样的UI控件。