Angular 12. 错误 TS2339:属性 'value' 在类型 'EventTarget' 上不存在

Angular 12. error TS2339: Property 'value' does not exist on type 'EventTarget'

我正在关注专业 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:

 <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,
...
]

在 (change) 里面,你应该只传递 $event。里面的逻辑,你应该取 event.target.value

如angulardocumentation

所述

When using $event.target for DOM events (because of the possibility of event bubbling, $event.target in the DOM typings doesn't have the type you might expect) in that case we can use $any() type-cast function opt out of type-checking for a part of the expression

<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>