【问题标题】:Angular 12. error TS2339: Property 'value' does not exist on type 'EventTarget'Angular 12. 错误 TS2339:“EventTarget”类型上不存在属性“值”
【发布时间】:2021-10-22 09:01:13
【问题描述】:

我正在关注 pro angular 6 第 3 版书籍教程,我发现很难解决 $event.target 值的问题。它被认为是限制每页显示的文章数量的一个选项。但我无法让它工作,我现在认为我的主要问题是该功能在 Angular 12 中不再可用。

ts代码如下:

...

changePage(newPage: number){
    this.selectedPage = newPage;
}

changePageSize(newSize: number){
    this.productsPerPage = Number(newSize);
    this.changePage(1);
}

get pageNumbers(): number[]{
    return Array(Math.ceil(this.repository.getProducts(this.selectedCategory)
      .length / this.productsPerPage)).fill(0).map((x, i)=> i +1);
 } 

...

enter code here

html 模板部分有问题 ...

 <select class="form-control" [value]="productsPerPage"
    (change)="changePageSize($event.target.value)">
        <option value="3">3 per Page</option>
        <option value="4">4 per Page</option>
        <option value="6">6 per Page</option>
        <option value="8">8 per Page</option>
    </select>

... 我感谢任何可能有帮助的解决方案。

【问题讨论】:

标签: html angular typescript select angular-directive


【解决方案1】:

为什么你不直接放:

HTML:

 <select class="form-control" [(ngModel)]="productsPerPage">
        <option value="3">3 per Page</option>
        <option value="4">4 per Page</option>
        <option value="6">6 per Page</option>
        <option value="8">8 per Page</option>
    </select>

注意:您必须在模块中导入 NgModule。

例如,在您的 app.module.ts 中:

...
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
...


imports: [
...
    FormsModule,
...
]

【讨论】:

  • 嗨,胡安,你是一个超级英雄,我不知道为什么我没有想到这一点,但非常感谢你,它工作得很好。
【解决方案2】:

如角度documentation中所述

当使用 $event.target 处理 DOM 事件时(因为可能 事件冒泡,DOM 类型中的 $event.target 没有类型 你可能会想到)在这种情况下,我们可以使用 $any() 类型转换函数选择退出对表达式的一部分进行类型检查

<select class="form-control" [value]="productsPerPage"
    (change)="changePageSize($any($event.target.value))">
        <option value="3">3 per Page</option>
        <option value="4">4 per Page</option>
        <option value="6">6 per Page</option>
        <option value="8">8 per Page</option>
 </select>

【讨论】:

  • 虽然我确实从下面胡安的解决方案中得到了解决方案,但我仍然尝试了您的解决方案,但恐怕它并没有解决我的问题。非常感谢:)
【解决方案3】:

inside (change),你应该只传递 $event。内部逻辑,你应该采取 event.target.value

【讨论】:

  • Nikhil,我在发布这个问题之前已经尝试过了,但没有成功。下面 Juan 建议的更改是有效的。
猜你喜欢
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 2017-06-23
  • 2021-12-01
相关资源
最近更新 更多