没有看到任何好的解决方案,但我确实做了一个解决方法,在下面发布,以防其他人有这个问题。请注意,这是一种解决方法,而不是正确的解决方案。
在这种情况下,我在页面上制作了一个隐藏表单,并正式创建了一个假文件上传字段,以模拟隐藏表单上传字段的事件。
假上传.component.ts
import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/material';
import { CustomTemplateOptions } from '../../../../../../kup-core/src/lib/models';
@Component({
selector: 'app-fake-upload-field',
template: `
<div>
<button
(click)="onClick()"
[id]="id"
type="file"
[formControl]="formControl"
[formlyAttributes]="field"
(change)="onChange()"
ngDefaultControl
[name]="id"
mat-stroked-button
>
Choose File
</button>
<input
type="text"
[value]="to.data.filename"
class="fake-file-upload-input"
(change)="onChange()"
/>
</div>
`,
styles: [
`
.fake-file-upload-input {
padding: 0;
margin: 0;
border: none;
}
`
]
})
export class FakeUploadComponent extends FieldType {
to: CustomTemplateOptions;
onClick() {
document.getElementById('realFileUpload').click();
}
onChange() {}
}
然后手动将文件值添加回正式表单模型中,
然后隐藏表单提交按钮创建了一个假表单提交面板,以老式方式模拟表单的事件和验证。
onHiddenFileUploadChange($event) {
const el: any = document.querySelector('.fake-file-upload-input');
this.stagedFile = $event.target.files;
this.stagedFilename = $event.target.files[0].name;
el.value = this.stagedFilename;
this.checkForm();
}
triggerSave() {
const form: HTMLElement = document.getElementById('importForm');
const button: HTMLElement = form.querySelector('button[type=submit]');
button.click();
}
private onImportTypeChanged(value: FormlyFieldConfig[]): void {
this.viewModel.importTypes.map(type => {
if (type.name === value[0].formControl.value) {
value[1].formControl.patchValue(type.description);
this.stagedType = type.name;
} else if (!value[0].formControl.value) {
this.stagedType = '';
}
});
}
这是我能找到解决formly 缺乏遗留支持的唯一方法,而不是直接分叉和定制它。