Reputation: 690
tl;dr:
How can I trigger <input file=type>
in this case without using nativeElement.click?. In better accordance with Renderer2 in other words
The idea of working with a dom element object in angular4+ component class isn't clear for this use case. This works in the current browser.
Specifically, this.picInput.nativeElement.click(); But this as I understand it is not recommended (using the element method directly ie. nativeElement.click()). Because it will not work in other platforms.
app.component.html
<!-- button element not hidden -->
<div fxFlex="10" style="text-align: center;">
<a md-raised-button (click)="clickTheInput()">Add Pic</a>
</div>
<!-- input element hidden on the page -->
<div class="row2ofheader">
<div fxFlex="10" style="text-align: center;">
<input #picInput type="file" (change)="alert('changed in input')">
</div>
</div>
app.component.ts
export class AppComponent implements OnInit, AfterViewInit {
@ViewChild('picInput') picInput;
constructor(private _auth: AuthService, private renderer: Renderer2) { }
ngAfterViewInit(): void {}
alert(input) {
window.alert(input);
}
clickTheInput() {
this.picInput.nativeElement.click();
}
Upvotes: 1
Views: 917
Reputation: 28708
From the docs:
A template reference variable is often a reference to a DOM element within a template. .... You can refer to a template reference variable anywhere in the template.
So #picInput gives you that reference to <input>
tag as DOM element properties and methods within the template.
You might want consider also this:
.....
<a md-raised-button (click)="picInput.click()">Add Pic</a>
.....
<input #picInput type="file" (change)="alert('changed in input')">
There is an other way to make it sure it works everywhere. Call the same method from both button and input:
HTML:
.....
<a md-raised-button (click)="onChange()">Add Pic</a>
.....
<input #picInput type="file" (change)="onChange()">
Typescript:
onChange(){
console.log("input changed")
}
If you need to detect which one of them fired onChange(), pass an argument:
<input #picInput type="file" (change)="onChange($event, 'input')">
or if you need to do something after but different from the other:
<input #picInput type="file" (change)="onChange(): somethingElse()">
Upvotes: 2