javascript - 错误类型错误:无法在 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');
}
解决方案
使用this
in your(click)="clickHandler(this)"
并不指代元素。它将参考class Properties
. 错误是因为element
on 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
}
}
推荐阅读
- c++ - 排序数组的快速排序控制台崩溃
- html - 如何将网站标题移动到横幅图片上方
- aerospike - 访问二级索引 Aerospike_ERR_INDEX_NOT_READABLE 时 Aerospike 出错
- twitter-bootstrap - 具有相同宽度的响应式卡片组
- c# - 如何检查是否已在 WPF 项目中使用 MAPI 发送邮件?
- mysql - 在 PowerShell 脚本中运行 MySQL 查询
- django - 在 Heroku 和 Django 应用程序上添加迁移的问题
- java - 在序列化 Spring Boot 应用程序中的任何响应时,如何让 Jackson 考虑 @JsonView?
- c# - 如何检查 MongoDB C# 中的索引(是否存在),因为 IndexExist 已从较新版本中弃用
- spring-boot - 使用 kotlin 时如何将 @RequestParams 传递给嵌套的 POJO