Reputation:
I can't get the file name from the File Input @angular/material component app.component.html
<div class="col-6">
<mat-form-field>
<ngx-mat-file-input [formControl]="fileControl"
placeholder="Выберите файл"
>
<mat-icon ngxMatFileInputIcon>folder</mat-icon>
</ngx-mat-file-input>
</mat-form-field>
</div>
The example is taken from the documentation for this component, so I did not change anything in it. Here are the modules that are in the file app.module.ts
imports: [
BrowserModule,
BrowserAnimationsModule,
CommonModule,
MatDatepickerModule,
MatInputModule,
FormsModule,
ReactiveFormsModule,
MatButtonModule,
MatRadioModule,
MatSelectModule,
MatCheckboxModule,
MatIconModule,
MatCardModule,
NgxMatFileInputModule,
],
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
fileName: string;
fileControl: FormControl;
// files: any;
files: FormControl;
constructor() {
this.fileName = '';
this.fileControl = new FormControl(this.files);
}
ngOnInit(): void {
this.fileControl.valueChanges.subscribe((files: FormControl) => {
console.log('valueChanges OK ');
this.files = files;
console.log('file = ' + this.files.value);
fileName = this.files.value; //error!!!
})
}
}
How do I get the file name here:
fileName = this.files.value ???
I took this example as a basis. example I removed everything unnecessary from there. I left only the code that is in my question
Upvotes: 0
Views: 657
Reputation: 130
I tried this solution with your repository!
app.component.ts file:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
fileControl: FormControl;
public file;
filename = '';
constructor() {
this.fileControl = new FormControl(this.file);
}
ngOnInit() {
this.fileControl.valueChanges.subscribe((file: File) => {
this.file = file;
this.filename = file.name;
console.log('fileName = ' + this.filename);
})
}
}
app.component.html file:
<div class="col-6">
<mat-form-field>
<ngx-mat-file-input [formControl]="fileControl">
<mat-icon ngxMatFileInputIcon>folder</mat-icon>
</ngx-mat-file-input>
</mat-form-field>
</div>
Upvotes: 1
Reputation: 2937
Use within reactive form. It will give you back an object with a 'files' array.
Wrap input element in form
<form *ngIf="fileForm" [formGroup]="fileForm">
<mat-form-field>
<ngx-mat-file-input [formControl]="fileControl" placeholder="Выберите файл">
<mat-icon ngxMatFileInputIcon>folder</mat-icon>
</ngx-mat-file-input>
</mat-form-field>
</form>
And in TS component file write selector
const file_form: FileInput = this.fileForm.get('fileControl').value;
Upvotes: 1