angular2-img-cropper
angular2-img-cropper copied to clipboard
Cannot read property 'setImage' of undefined
I'm trying to show user image to crop it after drop event and I'm getting the error (Angular2):
EXCEPTION: Cannot read property 'setImage' of undefined
This is my component:
import { ImageCropperComponent, CropperSettings } from 'ng2-img-cropper';
export class SomeComponent {
...
@ViewChild('cropper', undefined) cropper: ImageCropperComponent;
public cropperSettings: CropperSettings = new CropperSettings();
public croppingData: { [ key: string ]: any } = {};
...
constructor(private elementRef: ElementRef) {
this.cropperSettings.noFileInput = true;
this.cropperSettings.width = 200;
this.cropperSettings.height = 200;
this.cropperSettings.croppedWidth = 200;
this.cropperSettings.croppedHeight = 200;
this.cropperSettings.canvasWidth = 500;
this.cropperSettings.canvasHeight = 300;
this.cropperSettings.minWidth = 10;
this.cropperSettings.minHeight = 10;
this.cropperSettings.rounded = false;
this.cropperSettings.keepAspect = false;
this.cropperSettings.cropperDrawSettings.strokeColor = 'rgba(255,255,255,1)';
this.cropperSettings.cropperDrawSettings.strokeWidth = 2;
};
public onDrop(dragEvent: DragEvent): void {
let fileReader: FileReader = new FileReader();
fileReader.readAsDataURL(dragEvent.dataTransfer.files[0]);
fileReader.onload = (fileReaderEvent: any) => {
let wrapper: HTMLDivElement = this.findCroppingContainer();// returns DOM element
if (wrapper) {
let image: any = new Image();
image.src = fileReaderEvent.target.result;
this.cropper.setImage(image);// <-- this is the problem
}
};
dragEvent.stopPropagation();
dragEvent.preventDefault();
};
}
This is my template of this component:
<div class="imageWrapper">
<img-cropper [image]="croppingData" [settings]="cropperSettings"></img-cropper>
<img [src]="croppingData.image" title="Uploaded image" alt="Uploaded image" *ngIf="croppingData.image">
</div>
this is because when you image.src = fileReaderEvent.target.result; image is still not ready before the onload event fires. so try this way
..
if (wrapper) {
let image: any = new Image();
image.onload = function() {
this.cropper.setImage(image);
}
image.src = fileReaderEvent.target.result;
}
@kim-cph your solution not working for me
it happened to me when I removed the this.data = {}; of the constructor, just add it again.
@WeekendMan did you solve the problem, I am facing the same problem in 0.9.0 version in angular 4.4.6. any solution?
I have fixed with @ViewChild(ImageCropperComponent) cropper:ImageCropperComponent;
. now its working for me