正在尝试从父组件中的垫子对话框角度接收文件



我正在尝试从有文件输入的mat对话框接收文件。但也有一些问题。请帮帮我。

父组件.ts:

export class TimelineComponent implements OnInit {
cvList = [];
ngOnInit() {
}
addCv() {
const dialogNew = this.dialog.open(NewCvDialogComponent, {
data: {...this.cvList}
});
dialogNew.afterClosed().subscribe(result => {
if (result) {
this.cvList.push(result);
}
});
}
}

Mat对话框组件.html:

<div class="dialog">
<h2 mat-dialog-title>Attach CV</h2>
<form fxLayout="column" #form="ngForm">
<input
type="file"
accept=".doc,.docx,.txt,.pdf"
placeholder="Input file"
name="input-file"
[(ngModel)]="data.file"
(change)="addCV($event)"
required
/>
</form>
<div
mat-dialog-actions
fxLayout="row nowrap"
fxLayoutGap="10px"
class="actions"
>
<button
mat-raised-button
color="warn"
[mat-dialog-close]="false"
fxFlex="50"
>
Cancel
</button>
<button
mat-raised-button
color="primary"
[mat-dialog-close]="data"
cdkFocusInitial
fxFlex="50"
[disabled]="form.invalid"
>
Save
</button>
</div>
</div>

但如果我使用这个结果,我得到的只是文件名。我想接收所有带有名称、大小等的对象。我该怎么做?

已解决。在对话框组件中,我只添加了一个带有输入文件的变量,并使用[mat dialog close]将其传递给父级

您是否将文件路径设置为字符串?解决方案是将文件更改为字符串,并将数据传递到父组件中。

mat dialogy.component.ts中添加此文件事件函数

convertTostring(event){

let reader = new FileReader();
if(event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.cvv = reader.result;
};
}
}

mat dialogy.component.html

并将模板更改为[mat dialog close]="[data,cvv]">

<button
mat-raised-button
color="primary"
[mat-dialog-close]="[data, cvv]"
cdkFocusInitial
fxFlex="50"
[disabled]="form.invalid">
Save
</button>

最后,您可以在parent.component.ts中获取数据

addCv() {
const dialogNew = this.dialog.open(NewCvDialogComponent, {
data: {...this.cvList}
});
dialogNew.afterClosed().subscribe(data => {
if (result) {
console.log(data);
}
});
}

最新更新