Проблема с изменением размера и кадрированием изображения из пакета @ alyle / ui Angular 6 - PullRequest
0 голосов
/ 21 сентября 2018

ScreenShot

Нажатие Выбор файла * Кнопка 1007 *, в консоли показывалось, что она загружена, затем после нажатия на кнопку обрезки отображалась ошибкаконсоль как

UploadImageComponent.html:63 ERROR TypeError: Cannot read property 'crop' of undefined
    at UploadImageComponent.push../src/app/upload-image/upload-image.component.ts.UploadImageComponent.crop (upload-image.component.ts:69)
    at Object.eval [as handleEvent] (UploadImageComponent.html:63)
    at handleEvent (core.js:10251)
    at callWithDebugContext (core.js:11344)
    at Object.debugHandleEvent [as handleEvent] (core.js:11047)
    at dispatchEvent (core.js:7710)
    at core.js:8154
    at HTMLButtonElement.<anonymous> (platform-browser.js:988)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3811)

app.module.ts

import { BrowserModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { UploadImageComponent } from './upload-image/upload-image.component';

/** Alyle UI */
import {
  LyThemeModule,
  LyCommonModule,
  LY_THEME_CONFIG,
  LyThemeConfig,
  LyHammerGestureConfig,
  PartialThemeConfig} from '@alyle/ui';
import { MinimaTheme, MinimaLight, MinimaDark } from '@alyle/ui/themes/minima';
import { LyButtonModule } from '@alyle/ui/button';
import { LyResizingCroppingImageModule } from '@alyle/ui/resizing-cropping-images';
import { LyIconButtonModule } from '@alyle/ui/icon-button';
import { LyIconModule } from '@alyle/ui/icon';


@NgModule({
  declarations: [
    AppComponent,
    UploadImageComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    LyCommonModule,
    LyThemeModule.setTheme('minima-light'),
    LyResizingCroppingImageModule,
    LyButtonModule,
    LyIconButtonModule,
    LyIconModule
  ],
  providers: [
    { provide: HAMMER_GESTURE_CONFIG, useClass: LyHammerGestureConfig },
    { provide: LY_THEME_CONFIG, useClass: MinimaTheme } // theme
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

upload-image.component.ts

import { Component, OnInit } from '@angular/core';
import { UploadImageService } from '../shared/upload-image.service';
import { BrowserModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
/** Alyle UI */
import {
  LyThemeModule,
  LyCommonModule,
  LY_THEME_CONFIG,
  LyThemeConfig,
  LyHammerGestureConfig,
  PartialThemeConfig} from '@alyle/ui';
import { LyResizingCroppingImagesConfig, LyResizingCroppingImages, CroppedImage } from '@alyle/ui/resizing-cropping-images';

@Component({
  selector: 'app-upload-image',
  templateUrl: './upload-image.component.html',
  styleUrls: ['./upload-image.component.css'],
  providers:[UploadImageService]
})
export class UploadImageComponent implements OnInit {
  imageUrl: string = "/assets/img/default-image.png";
  fileToUpload: File = null;
  errorMsg: string;
  constructor(private imageService : UploadImageService) { }

  ngOnInit() {
  }

  img: LyResizingCroppingImages;
  result: string;
  myConfig: LyResizingCroppingImagesConfig = {
    width: 150, // Default `250`
    height: 150 // Default `200`
  };
  crop() {
    const imgCropped: CroppedImage = this.img.crop();
  }
  oncropped(e) {
    console.log('cropped', e);
  }
  onloaded() {
    console.log('img loaded');
  }
  onerror() {
    console.warn('img not loaded');
  }

}

upload-image.component.html

<style>
  ly-cropping {
    max-width: 400px;
    height: 300px;
  }


  .github {
    position: fixed;
    top: 0;
    right: 0;
    margin: 16px;
  }
</style>

<div lyTheme="minima-light">
    <h1>Angular resizing & cropping image </h1>

    <button ly-button color="accent" (click)="_fileInput.click()" raised>
      <ly-icon>image</ly-icon>
      <span>Select File</span>
    </button>

    <!-- Hidden input -->
    <input #_fileInput type="file" (change)="cropping.selectInputEvent($event)" accept="image/*" hidden>

    <br />
    <div class="resize-image">
      <button (click)="cropping.zoomIn()" ly-icon-button class="material-icons">zoom_in</button>
      <button (click)="cropping.zoomOut()" ly-icon-button class="material-icons">zoom_out</button>
      <button (click)="cropping.center()" ly-button>center</button>
      <button (click)="cropping.fit()" ly-button>fit</button>
      <button (click)="cropping.fitToScreen()" ly-button>fit to screen</button>
      <ly-cropping #cropping
      [config]="myConfig"
      (cropped)="oncropped($event)"
      (loaded)="onloaded()"
      (error)="onerror()">
        <span>Drag and drop image</span>
      </ly-cropping>
      <button *ngIf="cropping.isLoaded" color="accent" (click)="crop()" ly-button raised>crop</button>
</div>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--***Ignore***-->
<div class="github"><iframe allowtransparency="true" scrolling="no" frameborder="0" src="https://buttons.github.io/buttons.html#href=https%3A%2F%2Fgithub.com%2FA-l-y-l-e%2FAlyle-UI&data-text=Star&data-icon=octicon-star&data-size=large&data-show-count=true&aria-label=Star%20A-l-y-l-e%2FAlyle-UI%20on%20GitHub" style="width: 95px; height: 28px; border: none;"></iframe></div>

Все остальные функции, такие как Zoom In, Zoom Out, Center, Fit, Fit to Screen, работали идеально

Как мне нужно разрешить TypeError: Невозможно прочитать свойство 'crop' из неопределенного?

Обновление: HAMMER.JS успешно загружено после добавления его в angular.json и перекомпиляции с терминала

1 Ответ

0 голосов
/ 21 октября 2018

Используйте ViewChild для доступа дочерний LyResizingCroppingImages

stackblitz

пример:

@Component({
...
})
export class MyComponent {
  @ViewChild(LyResizingCroppingImages) img: LyResizingCroppingImages;// <= here
  crop() {
    const imgCropped: CroppedImage = this.img.crop()
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...