How to create a custom input file in Ionic 2+ using a button style?

Here is my template:

<label>{{label}}</label> <input type="file" (change)="fileUpload($event)" id="file-input" style="position:absolute; top: -999999px" #fileInp> <button ion-button (click)="onClick()">Upload</button> 

and ts file:

 @ViewChild('fileInp') fileInput: ElementRef; @Input() label: string; @Output() data = new EventEmitter<FormData>(); fileUpload(event) { let fd = new FormData(); fd.append('file', event.srcElement.files[0]); this.data.emit(fd); } onClick() { this.fileInput.nativeElement.click(); } 

Everything works fine on Android and in the browser, but not on iOS. The same code works if I disable the button in the template.

+6
source share
3 answers

You cannot click on a file entry in iOS. A workaround is to use css to set the opacity of the input element to 0 and place it only on top of the button. Thus, the input to the file will not be displayed, but when the button is pressed, it will be pressed.

 <ion-item> <label>{{label}}</label> <input type="file" (change)="fileUpload($event)" id="file-input" style="opacity: 0" #fileInp> <button ion-button (click)="onClick()">Upload</button> </ion-item> 

and then in the .scss file:

 #file-input { opacity: 0; position: absolute; top: 0; width: 100%; height: 100%; left: 0; z-index: 999; } 

There may be some other ways to fix this problem, but the way I did in the application I worked on in the past.

+6
source

The best way I've found this is to use a label with the for attribute and configure it with css. Therefore, when the user clicks on the label, the entry starts. Keep in mind that the for label must be an input identifier.

 <label class="myFakeUploadButton" for="myFileInput">Upload</label> <input type="file" id="myFileInput"> 
 #myFileInput{ position: absolute; opacity: 0; } .myFakeUploadButton{ /* Whatever you want */ } 
+1
source

I usually do the following.

  <ion-item> <ion-label color="primary" position="stacked">URL do vΓ­deo no youtube</ion-label> <ion-input [(ngModel)]="product.videoUrl"></ion-input> </ion-item> <ion-item> <ion-button color="primary" (click)="inputFile.click()"> <ion-icon name="attach"></ion-icon> Anexar documentos </ion-button> <input #inputFile id="input-file" style="opacity:0" type="file" (change)="uploadFiles($event)" multiple/> </ion-item> 
0
source

Source: https://habr.com/ru/post/1269056/


All Articles