【发布时间】:2021-10-04 04:19:38
【问题描述】:
我很难理解这种类型的角度错误:(TS) 元素隐式具有“任何”类型,因为“setAttribute”类型的表达式不能用于索引类型 EventTarget。 EventTarget 类型上不存在属性“setAttribute”。
我正在做一个项目,我有一个 SVG 地图并且它是交互式的。我将鼠标悬停在一个国家/地区上,它会从 api 中提取有关该国家/地区的数据。下面是一个sn-p。但是我在 map-image.component.ts 的 e.target["setAttribute"]("fill", "red") 上收到编译错误。我不明白我做错了什么,也找不到该错误的含义。
然后我将 e 更改为 any:
pieces.forEach((e: any) => {
e.addEventListener("mouseenter", e =>
e.target["setAttribute"]("fill", "red")
);
编译错误已修复,但没有从 api 中提取数据。
map-service.ts:
getCountry(countryCode: string) {
return this
.http
.get("https://api.worldbank.org/v2/country/" + countryCode + "?format=json");
}
map-image.component.ts:
export class MapImageComponent implements AfterViewInit {
@Output() onSelection: EventEmitter<any> = new EventEmitter();
ngAfterViewInit() {
let pieces = Array.from(document.querySelectorAll("path"));
pieces.forEach(e => {
e.addEventListener("mouseenter", e =>
e.target["setAttribute"]("fill", "red")
);
map.component.ts:
loadCountryData(e: any) {
this.country.name = e.name;
this.mapService
.getCountry(e.countryCode)
.pipe(take(1))
.subscribe((response: any) => {
this.country.data = [
"Name: " + response[1][0].name,
"Capital: " + response[1][0].capitalCity,
"Region: " + response[1][0].region.value,
"Income Level: " + response[1][0].incomeLevel.value
];
});
}
map.component.html:
<div class="row columns">
<div class="col pr-5">
<app-map-image (onSelection)="loadCountryData($event)"></app-map-image>
</div>
<div class="col-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ country?.name }}</h5>
<div class="card-text">
<ul>
<li *ngFor="let o of country?.data || []">
{{ o }}
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
【问题讨论】:
-
您的 .tsconfig 中可能已将
noImplicitAny设置为 true -
我在您的 html 中看不到任何
path元素。你确定你得到任何对象吗? -
作为一个警告,直接 DOM 操作在 Angular 中是一种非常反模式。这肯定不是实现您想要的行为的方法。
标签: angular events binding handler