I am implementing the following custom component to upload files:
I need to know how I can associate a NgModel
with the custom component that I create, to be able to handle it more easily and store the path of the file that was uploaded to be able to access it as an attribute as if it were a <input>
normal.
I leave the code of the package that I have so far.
file-input.component.ts
@Component({
selector: 'file-input',
templateUrl: './file-input.component.html',
styleUrls: ['./file-input.scss']
})
export class FileInputComponent implements OnInit, OnDestroy {
@BlockUI() blockUI: NgBlockUI;
@Input() placeholder: string;
@Input() codSubproyecto: string;
public subproyecto: any;
public subproyecto$: Subscription;
public filePath: string;
public fileName: string;
constructor(
private multimediaService: MultimediaService,
private subProyectosService: SubProyectosService
) {
this.fileName = '';
this.filePath = '';
}
ngOnInit() {
this.subproyecto$ = this.subProyectosService.getByCodigo(this.codSubproyecto).subscribe(_subproyecto => {
this.subproyecto = _subproyecto;
});
}
ngOnDestroy() {
if (this.subproyecto$) {
this.subproyecto$.unsubscribe();
}
}
public onFileChange($event) {
if ($event.target.files.length === 1) {
let file = $event.target.files[0];
this.fileName = file.name;
let data = {
codProyecto: this.subproyecto.CodProyecto,
codSubproyecto: this.codSubproyecto,
codFase: 'COD_VIABILIDAD',
};
this.blockUI.start('subiendo archivo...');
this.multimediaService.uploadFileHandle(data, file).subscribe(response => {
this.filePath = response.FileUri;
console.log(response.FileUri);
this.blockUI.stop();
},
error => {
this.filePath = '';
console.error(error);
});
} else {
this.fileName = '';
this.filePath = '';
}
}
}
file-input.component.html
<div>
<md-input-container class="input-file">
<input mdInput [placeholder]="placeholder" [(ngModel)]="fileName" [disabled]="true">
</md-input-container>
<button
type="button"
(click)="fileInforme.click()"
class="file-button"
md-mini-fab>
<md-icon>cloud_upload</md-icon>
</button>
<i class="fa fa-check icon-green fa-lg" style="padding-left: 10px" *ngIf="filePath.length > 0"></i>
<input #fileInforme type="file" style="display: None;" (change)="onFileChange($event)">
</div>
<block-ui></block-ui>