[英]Angular 2 trigger file upload in parent component
i want to trigger file upload in router parent component. 我想在路由器父组件中触发文件上传。 It should call two functions that are present in parent,
openFileSelect
and uploadSelectedFile
to control the <input type="file">
element. 它应该调用父级中存在的两个函数
openFileSelect
和uploadSelectedFile
来控制<input type="file">
元素。
My router looks like this: 我的路由器如下所示:
{
path: '',
component: HomeComponent,
canActivate: [AuthService],
children: [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'upload',
component: UploadComponent
}
]
}
The file input is in HomeComponent.html template and router-outlet where the child component is displayed: 输入的文件位于HomeComponent.html模板和router-outlet中,其中显示子组件:
<div class="container">
<input type="file" (change)="fileChangeEvent($event)" #fileUpload>
<router-outlet></router-outlet>
</div>
Then in HomeComponent.ts i have: 然后在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 ...
}
}
At the end i want to trigger the same openFileSelect method from HomeComponent inside UploadComponent 最后,我想从UploadComponent内的HomeComponent触发相同的openFileSelect方法
import { Component } from "@angular/core";
@Component({
templateUrl: "upload.component.html",
})
export class UploadComponent {
constructor() { }
openFileSelectInHomeComponent() {
// TODO - how to call HomeComponent.openFileSelect() ?
}
}
So i have two questions: 所以我有两个问题:
How to programmatically trigger click event on ? 如何以编程方式触发on的click事件?
And how to call function from child component to router parent component? 以及如何从子组件到路由器父组件调用函数?
There is a similar answer to your question here: jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox? 您的问题在这里有类似的答案: jQuery:模拟对<input type =“ file” />的单击在Firefox中不起作用?
Maybe it will give you an idea. 也许会给你一个主意。 Or you can use a UI control like primeNg's FileUpload control.
或者,您可以使用诸如primeNg的FileUpload控件之类的UI控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.