Как исправить «ОШИБКА TypeError: Не удается прочитать свойство 'style' of undefined" - PullRequest
1 голос
/ 21 мая 2019

Я делаю ползунок сравнения изображений в угловом формате, но получаю эту ошибку "ОШИБКА TypeError: Невозможно прочитать свойство 'style' of undefined"

Поэтому я подумал, что элементы не должны быть загружены в DOM, поэтомуя завернул его в ngAfterViewInit(), но он все еще не работает, и я получаю ту же ошибку

это HTML-код

<section id="comparison-slider" class="comparison-slider">
  <div class="picture picture--before">
    <div class="picture__content-wrap">
      <div class="picture_content">
        <h3>random txt</h3>
      </div>
      <img src="../../assets/imgs/wwu/Untitled-1.gif" alt="1">
    </div>
  </div>

  <div class="picture picture--after">
    <div class="picture__content-wrap">
      <div class="picture_content">
        <h3>random txt</h3>
      </div>
      <img src="../../assets/imgs/wwu/Untitled-1.gif" alt="2">
    </div>
  </div>
  <div class="handle">

  </div>
</section>

это код TS

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-wwu',
  templateUrl: './wwu.component.html',
  styleUrls: ['./wwu.component.scss']
})
export class WwuComponent implements OnInit {

  constructor() { }

  ngOnInit() { 
  }

  ngAfterViewInit() {

let comparisonSlider = document.getElementById('comparison-slider');
    let pictureAfter: HTMLElement = document.getElementsByClassName('.picture--after')[0] as HTMLElement;
    let handle: HTMLElement = document.getElementsByClassName('.handle')[0] as HTMLElement;
    let skew = 0;
    let delta = 0;

    if (comparisonSlider.className.indexOf('comparison-slider') != -1) { //if the section has a class ‘comparison-slider’ 
      skew = 2000;
    }

    comparisonSlider.addEventListener('mousemove', function (e) {
      delta = (e.clientX - window.innerWidth / 2) * 0.5; // distance between the mouse and the center of the section
      handle.style.left = e.clientX + delta + 'px'; // change handle position
      pictureAfter.style.width = e.clientX + skew + delta + 'px'; // change width of pictureAfter
    });

  }

}

и это журнал ошибок

core.js:15724 ERROR TypeError: Cannot read property 'style' of undefined
    at HTMLElement.<anonymous> (wwu.component.ts:32)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:498)
    at invokeTask (zone.js:1744)
    at HTMLElement.globalZoneAwareCallback (zone.js:1770)
defaultErrorLogger  @   core.js:15724
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError    @   core.js:15772
next    @   core.js:17771
schedulerFn @   core.js:13515
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub   @   Subscriber.js:196
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next   @   Subscriber.js:134
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next  @   Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next   @   Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @   Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit   @   core.js:13499
(anonymous) @   core.js:17321
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke    @   zone.js:391
push../node_modules/zone.js/dist/zone.js.Zone.run   @   zone.js:150
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular    @   core.js:17258
onHandleError   @   core.js:17321
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError   @   zone.js:395
push../node_modules/zone.js/dist/zone.js.Zone.runTask   @   zone.js:198
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask    @   zone.js:498
invokeTask  @   zone.js:1744
globalZoneAwareCallback

1 Ответ

3 голосов
/ 21 мая 2019

вы должны указать только имя класса в getElementsByClassname, но не . в качестве префикса

 let handle: HTMLElement = document.getElementsByClassName('.handle')[0] as HTMLElement;

должно быть

   let handle: HTMLElement = document.getElementsByClassName('handle')[0] as HTMLElement;

также удалить . в .picture - после

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...