【问题标题】:Event Binding using Angular on an HTML input element在 HTML 输入元素上使用 Angular 进行事件绑定
【发布时间】: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 中提取数据。

ma​​p-service.ts

  getCountry(countryCode: string) {

    return this

      .http

      .get("https://api.worldbank.org/v2/country/" + countryCode + "?format=json");

  }

ma​​p-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")

      );

ma​​p.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

          ];

        });

  }

ma​​p.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


【解决方案1】:

你需要告诉编译器e.target实际上是什么:

e.addEventListener("mouseenter", (event: MouseEvent) =>
  (event.target as HTMLElement).setAttribute("fill", "red");
);

您还隐藏了不利于可读性的 e 变量,因此我将其重命名为 event

我也不知道你的 e 元素实际上是什么,所以我只是把 HTMLElement 作为类型。例如,如果您使用 div 之类的东西,您可以将其更改为 HTMLDivElement,或与您拥有的元素对应的任何类型。可以保持原样,但在这种情况下添加更具体的类型不会有任何作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多