Consider a component of which the template include a file input. The input can be opened by calling a public open()
method which triggers a click on the nativeElement
of the input.
@Component({
selector: 'child',
template: '<input type="file" #input/>',
})
export class ChildComponent {
@ViewChild('input')
public input: ElementRef;
public open(): void {
console.log('OPENING THE FILE INPUT');
this.input.nativeElement.click();
}
}
This ChildComponent
is called in a ParentCompenent
, which calls ChildComponent.open()
in multiple contexts, as defined below :
@Component({
selector: 'parent',
template: '<child></child>',
})
export class ParentComponent {
@ViewChild(ChildComponent)
public child: ChildComponent;
constructor( private parentService: ParentService ) {
}
public openChildInput(): void {
// This works.
// Output:
// OPENING THE FILE INPUT
// The file input opens
this.child.open();
}
public waitAndOpenChildInput(): void {
parentService.wait()
.subscribe( () => {
// This does not work.
// Output:
// "OPENING THE FILE INPUT"
// The file input DOES NOT open...
this.child.open();
})
}
}
In both cases, calling the open()
method seems to work (as the console.log
does show); yet the file input seems unwilling to open itself when called from a subscription.
Any ideas why ? Thanks in advance...