我需要将File类型的输入中的值传递给我的ngModel对象。升级很容易,但是我无法在视图(双向)部分中更改该值。提交表单时,对象显示为未定义,如果我在启动组件时设置了对象,则当然需要根据用户选择的文件进行更改。
Html组件:
<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>
成分:
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({
...
})
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();
}
}
这个组件是我通过reactiveForm创建表单并定义表单输入的地方。问题出在具有inpu文件的组件中。如何对this.fileModel中的结果传递给这个表单的提交?通过ngModel做得很好,但输入文件不接受此类输入的运行时更改。