I am attempting to build a form that allows for file uploads using Angular (v12) and Formly (v5). I have referenced Formly File Input example and implemented my solution accordingly.
In app.module
the Formly config is as follows:
FormlyModule.forRoot({
validators: [
{
name: 'email',
validation: EmailValidator
},
{
name: 'zip',
validation: ZipValidator
}
],
extras: { lazyRender: true },
types: [
{ name: 'repeater', component: QuestionRepeaterComponent },
{ name: 'file', component: FormlyFieldFile, wrappers: ['form-field'] },
],
}),
The FormlyFieldFile
component:
import { FormControl } from '@angular/forms';
import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/material/form-field';
@Component({
selector: 'formly-field-file',
template: `
<input type="file" [formControl]="formControl" [formlyAttributes]="field">
`,
})
export class FormlyFieldFile extends FieldType {
formControl!: FormControl;
}
Note: I had to declare the formControl
property as a FormControl
to avoid a compiler error in Angular 12.
And FileValueAccessor
import { Directive } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Directive({
// tslint:disable-next-line
selector: 'input[type=file]',
host: {
'(change)': 'onChange($event.target.files)',
'(blur)': 'onTouched()',
},
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: FileValueAccessor, multi: true },
],
})
// https://github.com/angular/angular/issues/7341
export class FileValueAccessor implements ControlValueAccessor {
value: any;
onChange = (_: any) => { };
onTouched = () => { };
writeValue(value: any) { }
registerOnChange(fn: any) { this.onChange = fn; }
registerOnTouched(fn: any) { this.onTouched = fn; }
}
/** Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license */
The logic for building the form:
public buildDocUploadForm(docOptions: Array<DropdownOption>) {
var fFields = new Array<FormlyFieldConfig>();
var fileF = this.buildFormlyField("file", "upload", { label: "Document File", required: true });
var empF = this.buildFormlyField("input", "obj.empID", { label: "Employee ID", disabled: true, required: true });
var docID = this.buildFormlyField("native-select", "obj.doc.id", { label: "Document Type", required: true, options: docOptions });
var fNameF = {
key: 'obj.fileName',
type: 'input',
hideExpression: `model.obj.doc == undefined || model.obj.doc.id == '${this.HRDOC_OTHER_ID}'`,
templateOptions: {
label: 'Display Name'
}
};
fFields.push(fileF);
fFields.push(empF);
fFields.push(docID);
fFields.push(fNameF);
return fFields;
}
private buildFormlyField(type: string, key: string, templateOptions?: any, validators?: any,
hideExpression?: string, expressionProperty?: any) {
var f: any = {
key: key,
type: type,
templateOptions: templateOptions
};
if (validators) {
f["validators"] = validators;
}
if (hideExpression) {
f["hideExpression"] = hideExpression;
}
if (expressionProperty) {
f["expressionProperties"] = expressionProperty;
}
return f;
}
The actual form is in my UploadResourceDialogComponent
:
export class UploadResourceDialogComponent implements OnInit {
form = new FormGroup({});
fields: FormlyFieldConfig[] = [];
model: FileUpload = {
obj: new HrEmpDoc(this.data.empId),
upload: undefined
}
constructor(
@Inject(MAT_DIALOG_DATA) public data: { empId: string },
private uploadService: ResourceService,
private empService: EmployeeService,
private formlyBuilder: FormlyBuilderService,
private optBuilder: OptionBuilderService,
public dialogRef: MatDialogRef<UploadResourceDialogComponent>
) {
}
ngOnInit(): void {
this.uploadService
.getDocs()
.subscribe(res =>
this.fields = this.formlyBuilder.buildDocUploadForm(this.optBuilder.mapToDropdownOptions(res, "id", "title"))
);
}
onSubmit() {
if (this.form.valid) {
this.empService.addDoc(this.data.empId, this.model.upload!, this.model.obj)
.subscribe(res => this.dialogRef.close(true));
}
}
}
The HTML for the component
<h4>Add Resource </h4>
<form enctype="multipart/form-data" [formGroup]="form" (ngSubmit)="onSubmit()">
<formly-form [form]="form" [fields]="fields" [model]="model">
</formly-form>
{{model | json}}
<button mat-button>Submit</button>
</form>
... and the model used.
export interface FileUpload {
upload: File | undefined
obj: any
}
The form displays as expected. However, instead of coming through as a Blob, File, a byte array, etc, the file simply comes through as a string, i.e. the model for a completed form: { "obj": { "id": 0, "fileID": "", "createdDateTime": "2021-09-30T12:29:34.108Z", "empID": "1002397", "doc": { "isInternal": false, "docCat": "OT", "id": "I9" }, "fileName": "Test" }, "upload": "C:\\fakepath\\Screenshot_2021-06-08_13-39-01.png" }
What am I doing wrong? I have implemented file uploads in Angular previously (using just Reactive Forms) and never encountered this issue before?
value
of<input type="file">
contains a file path. I noticed that your implementation ofFileValueAccessor
actually does nothing, you are passing $event.target.files to onChange() but it's emptyFileValueAccessor
, I used the one provided in Stackblitz example from Formly : stackblitz.com/angular/… However, I might work on modifying it and seeing if I can get it working. Thanks.