繁体   English   中英

尝试从父组件中的 mat-dialog angular 接收文件

[英]Trying to receive file from mat-dialog angular in parent component

我正在尝试从具有文件输入的 mat-dialog 接收文件。 但是有一些问题。 请帮帮我。

父组件.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对话框component.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-dialogue.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-dialogue.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);
      }
    });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM