I need to pass a value from an input of type File to to an object in which is my ngModel. To upgrade was easy, but I'm not able to make that value change in the view (two-way) part. When submitting the form the object appears as undefined, if I set the object in hand when starting the component it works, however of course, it needs to be changed according to the file that the user selects.
Html component:
<div class="file-field input-field row col s12" [formGroup]="group">
<div class="btn">
<span>{{ config.label }}</span>
<input type="file"
[(ngModel)]="fileModel"
(change)="getImage($event)"
[formControlName]="config.name"
accept="{{ config.accept }}"
>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
component:
fileModel: FileModel;
getImage(event) {
if (event.target.files) {
var fileToUpload = event.target.files[0];
var fileReader = new FileReader();
var fileModel: FileModel;
var reader = new FileReader();
reader.onload = (function (theFile) {
var fileName = theFile.name;
return function (e) {
this.fileModel = new FileModel(fileName, e.target.result);
console.log(this.fileModel);
};
})(fileToUpload);
reader.readAsDataURL(fileToUpload);
}
}
}
Component in which you have the form and the submit:
@Component({
...
})
export class IwtiFuncionarioNovoComponent implements OnInit, AfterViewInit {
@ViewChild(DynamicFormComponent) iwtiFuncionarioNovoForm: DynamicFormComponent;
config: FieldConfig[] = [];
opcoesCargos = new Array<SelectData>();
opcoesSetores = new Array<SelectData>();
constructor(
...
) { }
ngOnInit() {
this.config.push(this.controlService.createInput('nome', 'input', 'text', 'Nome', true, [Validators.required]));
this.config.push(this.controlService.createSelectDropdownInput<Setor>('setorId', 'Setor', this.opcoesSetores, 'Selecione...', [Validators.required]));
this.config.push(this.controlService.createSelectDropdownInput<Cargo>('cargoId', 'Cargo', this.opcoesCargos, 'Selecione...', [Validators.required]));
this.config.push(this.controlService.createInput('username', 'input', 'text', 'Usuário', false, [Validators.required]));
this.config.push(this.controlService.createInput('password', 'input', 'password', 'Senha', false, [Validators.required]));
this.config.push(this.controlService.createInputFile('imagem', 'Foto', true));
this.config.push(this.controlService.createSubmitButton('Salvar', 'save'));
}
submit(iwtiFuncionarioForm: any) {
this.ambiente.invertBusy();
console.log(iwtiFuncionarioForm);
this.ambiente.invertBusy();
}
}
This component is where I create the form via reactiveForm and define the form inputs. The problem is in the component that has the inpu file. How to do to the result I have in this.fileModel pass to the submit of this form? Via ngModel does very well, but the input file does not accept the run-time change for this type of input.