首页 > 解决方案 > 错误类型错误:无法在 Component.clickHandler 处读取未定义的属性“添加”

问题描述

我目前正在研究 Angular 8。我在这里要做的是在选择 div 时更改它的颜色。但是当我点击 div 时,它给了我上面提到的错误。任何帮助将不胜感激

我的 HTML 代码

  <div class="icon text-custom-white bg-light-green" id="myDIV" (click)="clickHandler(this)">

                  <img
                  src="{{category?.CategoryImage || 'https://giftclubimagestorage.blob.core.windows.net/images/biryani.jpg'}}"
                  class="rounded-circle"
                  alt="{{category?.CategoryTitle || ''}}" class="imgrr">

            </div>

我的 CSS 代码

.icon {

}

.selected {

  border-color: 20px solid blue;

}

我的 TS 代码

  clickHandler(element) {
    // Get currently selected element(s)
    const old = document.getElementsByClassName('icon');

    
    for (let i = 0; i < old.length; i++) {
      // Remove current selected class
      console.log(old[i].classList.remove('selected'));
      }
    // On element that called the function add selected class
    element.classList.add('selected');
  }

标签: javascripthtmlangulartypescriptangular8

解决方案


使用thisin your(click)="clickHandler(this)"并不指代元素。它将参考class Properties. 错误是因为elementon element.classList.add('selected');is undefined

如果你想获得你的元素,Component.ts最好使用@viewChild

但是为了您的目的,最好使用像这个例子这样ngClass的简单变量:boolean

Stackblitz上的示例代码:

组件样式.css

.selected {
  border: solid 1px black;
  border-color: 20px solid blue;
}
.not-selected {
  border-color: none;
}

组件.template.html

<div (click)="toggle()" [ngClass]=" (isSelected) ? 'selected' : 'not-selected' ">Select Test</div>

组件.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
}) 

export class AppComponent  {

  public isSelected: boolean = false;

  toggle = () => {
    this.isSelected = !this.isSelected
  }
}

推荐阅读