微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

角度错误无法读取未定义的属性“样式”

如何解决角度错误无法读取未定义的属性“样式”

我正在尝试将 following slideshow 的 javascript 版本转换为在 Typescript 语言中使用,但遇到了一个问题:

我收到一条错误消息:

无法读取未定义的属性“样式”

它似乎不接受打字稿中的 slides[this.selectedindex - 1].style.display。所以我添加(<HtmlElement>...) 但它不起作用。

我已经实现了以下代码

home.component.ts

import { Component,OnInit,ViewChild } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { NgbCarousel,NgbSlideEvent,NgbSlideEventSource } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-home',templateUrl: './home.component.html',styleUrls: ['./home.component.css'],})
export class HomeComponent implements OnInit {
  title: string;
  description: string;
  role: Number;
  public selectedindex: number = 0;
  public images = ['../../assets/images/healthimage1.png','../../assets/images/healthimage2.jpg','../../assets/images/healthimage3.jpg'];
  
  selectimage(index: number) {
    console.log("Index: " + index);
    this.selectedindex = index;
    console.log("Selected Index: " + this.selectedindex);
  }

  showSlides() {
    let i;
    let slides = document.getElementsByClassName("mySlides");
    let dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
      (<HTMLElement>slides[i]).style.display = "none";
    }
    this.selectedindex++;
    if (this.selectedindex > slides.length) { this.selectedindex = 1 }
    for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active","");
    }
    (<HTMLElement>slides[this.selectedindex - 1]).style.display = "block";
    dots[this.selectedindex - 1].className += " active";
    setTimeout(this.showSlides,2000);
  }


  constructor(
    private activatedRoute: ActivatedRoute,private router: Router) {
    this.role = 1;

  }

  ngOnInit() {
      this.showSlides();
  }

}

home.component.html

<div *ngIf="images">
  <div class="mySlides slideshow-container">
      <img *ngFor="let image of images; let i=index" 
          [src]="image" 
          [ngClass]="{'image-active': selectedindex == i}">  

      <div style="text-align:center; display:inline-block;"  *ngFor="let dot of images; let i=index">
          <span class="dot" 
              (click)="selectimage(i)"
              [ngClass]="{'active': selectedindex == i}">
          </span>
      </div>
  </div>
</div>

css:

.slideshow-container {
  max-width: 1200px;
  position: relative;
  margin: auto;
  text-align:center;
}

.slideshow-container img{
  display: none;
}

.slideshow-container img.image-active {
    display: block;
    width: 100%;
}

/* The dots/indicators */
.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active,.dot:hover {
  background-color: #717171;
}

解决方法

stackblitz link中的工作演示

您需要在 angular 中引用 html 元素,以便在 angular 中进行 dom 操作。

html 模板是

<ng-container>
<h2>Automatic Slideshow</h2>
<p>Change image every 2 seconds:</p>

<div class="slideshow-container">

    <div #slides class="mySlides fade">
        <div class="numbertext">1 / 3</div>
        <img src="https://images.pexels.com/photos/6027869/pexels-photo-6027869.jpeg" style="width:100%">
        <div class="text">Caption Text</div>
    </div>

    <div #slides class="mySlides fade">
        <div class="numbertext">2 / 3</div>
        <img src="https://images.pexels.com/photos/3889926/pexels-photo-3889926.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" style="width:100%">
        <div class="text">Caption Two</div>
    </div>

    <div #slides class="mySlides fade">
        <div class="numbertext">3 / 3</div>
        <img src="https://images.pexels.com/photos/6027869/pexels-photo-6027869.jpeg" style="width:100%">
        <div class="text">Caption Three</div>
    </div>

</div>
<br>

<div style="text-align:center">
    <span #dot class="dot"></span>
    <span #dot class="dot"></span>
    <span #dot class="dot"></span>
</div>
</ng-container>

上面的#slides 和#dots 是模板引用变量。我们正在使用@ViewChildren() 从 component.ts 文件中获取多个幻灯片和点元素引用

component.ts 文件

slidesIndex = 0;
@ViewChildren("slides") slides: QueryList<ElementRef>;
@ViewChildren("dot") dots: QueryList<ElementRef>;
slider$;

ngAfterViewInit() {
  this.showSlides();
}

showSlides() {
  this.slides.forEach(
   (slidesDiv: ElementRef) =>
     (slidesDiv.nativeElement.style.display = "none")
   );
this.slidesIndex += 1;

if (this.slidesIndex > this.slides.length) {
  this.slidesIndex = 1;
}
this.dots.forEach(
  dotsDiv =>
    (dotsDiv.nativeElement.className = dotsDiv.nativeElement.className.replace(
      " active",""
    ))
);
this.slides.toArray()[this.slidesIndex - 1].nativeElement.style.display =
  "block";
this.dots.toArray()[this.slidesIndex - 1].nativeElement.className +=
  " active";
setTimeout(() => {
  this.showSlides();
},2000); // Change image every 2 seconds
}
,

您是否尝试使用 viewChild 而不是 document.getElementByClassName。

因此,在 html 中将 id 和 id 添加到您的幻灯片部分。

 <div class="mySlides slideshow-container" id="idSlides">

在您的角度组件中,您将幻灯片定义为

@ViewChild('idSlides',{ static: false })
    slides: Slides;

我认为,slides 的值不应该为 null 或 undefined。

Document.getElementById 用于 Javascript 而不是 angular

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?