考虑模板包含文件输入的组件。可以通过调用公共
open()
方法触发对
nativeElement
@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();
}
}
这
ChildComponent
ParentCompenent
,调用
ChildComponent.open()
在多个上下文中,定义如下:
@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();
})
}
}
在这两种情况下
打开()
console.log
不显示);然而,当从订阅调用时,文件输入似乎不愿意自己打开。
提前谢谢。。。