How to use input type file in angular material
Hi, I am using angular material for designing. when i go on angular material site there no input type fil
If you dont want to use some strange workaround, then just dont place input
into the mat-form-field
. You can place it outside the mat-form-field
but still include the value into the FormGroup
. Check the example
<form [formGroup]="someForm" (ngSubmit)="onSubmit()">
<!--input outside the form-field-->
<input type="file" (Change)="onChange($event)"/>
<mat-form-field>
<!--input inside the form-field-->
<input matInput formControlName="someFCN">
</mat-form-field>
<button mat-raised-button>Submit</button>
</form>
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
someForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.someForm = this.formBuilder.group({
someFCN: [{ value:'', disabled: false },Validators.required],
file: { value:'', disabled: false }
});
}
onChange(event: Event) {
/*not sure what you want to do with file, i'll just set
selected file´s name as value, but obviously u can do much more than just get file´s name.*/
this.someForm.controls['file'].setValue(event.target.files[0].name);
}
onSubmit() {
return this.someForm.getRawValue();
}
Angular Material does not support yet a workaround for file upload. There are alternative to archieve this. e.g using external libraries.
angular-material-fileupload: link to npm package
Supported features:
ngx-material-file-input: Link to repository
Supported features:
ngx-mat-file-input
component, to use inside Angular Material mat-form-field
FileValidator
with maxContentSize
, to limit the file sizeByteFormatPipe
to format the file size in a human-readable formatUpdate
See the answer here if you just need a workaround without external library https://stackoverflow.com/a/53546417/6432698
Here is a workaround if all you want is a nicely displayed file input button.
Html
<button type="button" mat-raised-button (click)="fileInput.click()">Choose File</button>
<input hidden (change)="onFileSelected()" #fileInput type="file" id="file">
Component
onFileSelected() {
const inputNode: any = document.querySelector('#file');
if (typeof (FileReader) !== 'undefined') {
const reader = new FileReader();
reader.onload = (e: any) => {
this.srcResult = e.target.result;
};
reader.readAsArrayBuffer(inputNode.files[0]);
}
}
Inspired by this Angular Material Github Issue comment https://github.com/angular/material2/issues/3262#issuecomment-309000588
I would suggest you to checkout @angular-material-components/file-input.
It is very Angular Material Compliant.