错误 TS2345:“事件”类型的参数不可分配给“字符串”类型的参数

时间:2021-04-02 10:57:53

标签: angular typescript

嗨,我是 angular 的新手,我似乎无法弄清楚我做错了什么。这是类型脚本代码。

import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      loadedFeature = 'recipe';
    
      onNavigate(feature: string) {
        this.loadedFeature = feature;
      }
    }

下面是html

<app-header (featureSelected)="onNavigate($event)"></app-header>
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <app-recipies *ngIf="loadedFeature === 'recipe'"></app-recipies>
      <app-shopping-list *ngIf="loadedFeature !== 'recipe'"></app-shopping-list>
    </div>
  </div>
</div>

下面是错误

Error: src/app/app.component.html:1:43 - error TS2345: Argument of type 'Event' is not assignable to parameter of type 'string'.

1 <app-header (featureSelected)="onNavigate($event)"></app-header>
                                            ~~~~~~

  src/app/app.component.ts:5:16
    5   templateUrl: './app.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component AppComponent.

2 个答案:

答案 0 :(得分:0)

onNavigate(feature: string) {
    this.loadedFeature = feature;
}

您将 feature 定义为 string 类型,这显然不是这种情况。检查 app-header 的文档并添加正确的类型。

更改为 any 现在应该可以解决您的问题,但强烈建议您正确输入。

答案 1 :(得分:0)

onSelect(feature: string){
        this.featureSelected.emit(feature);
    }

在 header.component.html 中检查这段代码 可能是