How to get the file name from File Input @angular/material

Viewed 691

I try to use the component @angular-material-components/file-input in the project on Angular I look at examples of its use: file-input

<mat-form-field>
   <ngx-mat-file-input [formControl]="fileControl">
   </ngx-mat-file-input>
</mat-form-field>

ts:

export class DemoFileInputComponent implements OnInit {
fileControl: FormControl;
constructor() {
    this.fileControl= new FormControl(this.files);
  }
 ngOnInit() {
    this.fileControl.valueChanges.subscribe((files: any) => {
      if (!Array.isArray(files)) {
        this.files = [files];
      } else {
        this.files = files;
      }
      console.log('valueChanges');
    })
}

Everything works on the form, I select the file, it appears in the input field. But I don't understand how I can get its name and full path in the code? The method this.fileControl.valuechanged.subscribe is not triggered when a file is selected

2 Answers

Use it like this

In your html file

<form [formGroup]="form" novalidate>

  <mat-form-field>
    <ngx-mat-file-input formControlName="file" placeholder="Basic Input">
    </ngx-mat-file-input>
  </mat-form-field>

</form>

And in your typescript file

ngOnInit() {
    this.form = this.fb.group({
      file: []
    });
    this.form.controls["file"].valueChanges.subscribe(el => {
      console.log(this.form.controls["file"].value.fileNames);
      //or
      console.log(el.fileNames);
    });
  }

When you subscribe and you get the file then the name would be on a field with name .fileNames

This should work:

export class DemoFileInputComponent implements OnInit {
  fileControl: FormControl;
  latestFile: File;
  filename = '';

  constructor() {
    this.fileControl = new FormControl(this.fileControl);
  }

  ngOnInit() {
    this.fileControl.valueChanges.subscribe((file: File) => {
      this.latestFile = file;
      this.filename = file.name;
      console.log('fileName = ' + this.filename);
    })
  }
}

If you don't need latestFile you can remove it:

export class DemoFileInputComponent implements OnInit {
    fileControl: FormControl = new FormControl();
    filename = '';

    constructor() { }

    ngOnInit() {
        this.fileControl.valueChanges.subscribe((file: File) => {
            this.filename = file.name;
            console.log('fileName = ' + this.filename);
        })
    }
}
Related