Now that we have a working preview service, we can use it in our dialog. In order to use it, we are going to pass it into our constructor. As the service is injectable, we can let Angular take care of injecting it for us as long as we add an appropriate reference in our constructor. At the same time, we are going to add in a reference to the dialog itself, as well as a set of declarations that will be used in the corresponding HTML template:
protected imageSource: IPictureModel | null;
protected message: any;
protected description: string;
protected tags: string;
constructor(
private dialog: MatDialogRef<FileuploadComponent>,
private preview: FilePreviewService) { }
With this reference in place, we are going to create a method to accept the file selection from the file upload component and call our Preview method. catch is in place to cater for our defensive coding in the service, as well as to cater for situations where the user tries to upload a non-image file. If the file is invalid, the dialog will show a message informing the user of this:
public OnImageSelected(files: any): void {
this.preview.Preview(files).then(r => {
this.imageSource = r;
}).catch(r => {
this.message = r;
});
}
The last thing we need to do with the code side of the dialog is to allow the user to close the dialog and pass the selected values back to the calling code. We update the image source description and tags with the relevant local values. The close method closes the current dialog and returns imageSource back to the calling code:
public Save(): void {
this.imageSource.Description = this.description;
this.imageSource.Tags = this.tags;
this.dialog.close(this.imageSource);
}