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.
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:
<div class="container">
<input type="file" (change)="fileChangeEvent($event)" #fileUpload>
<router-outlet></router-outlet>
</div>
Then in HomeComponent.ts i have:
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
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 ?
And how to call function from child component to router parent component?