簡體   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