代码之家  ›  专栏  ›  技术社区  ›  Amrmsmb

“Event”类型的参数不能赋值给“string”类型的参数

  •  0
  • Amrmsmb  · 技术社区  · 5 年前

    在下面的代码中,我想使用eventemitters来调用方法“onlyNewAddItems”。

    @Output() newItemValue = new EventEmitter<string>();
    
      addNewItem(val : string) {
        this.newItemValue.emit(val);
        console.log("add new item:" + val);
        this.items.push(val);
      }
    

    为了绑定到这个事件,我做了以下操作:

    <h1 (newItemValue) = onlyNewlyAddedItems($event)></h1>
    

    但是当我编译代码时,我收到以下错误

    Error: src/app/app.component.html:4:42 - error TS2345: Argument of type 'Event' is not assignable to parameter of type 'string'.
    
    4 <h1 (newItemValue) = onlyNewlyAddedItems($event)></h1>                                        
      src/app/app.component.ts:5:16
        5   templateUrl: './app.component.html',
                         ~~~~~~~~~~~~~~~~~~~~~~
        Error occurs in the template of component AppComponent.
        
    

    请让我知道如何通过eventemitter执行“onlyNewlyAddedItems”方法。

    应用组件.component.ts

    import { Component, Input, Output, EventEmitter } from '@angular/core';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'InputOutputBindings';
      currentItem = 'TV';
      items = ['item1', 'item2', 'item3', 'item4'];
    
      @Output() newItemValue = new EventEmitter<string>();
    
      addNewItem(val : string) {
        this.newItemValue.emit(val);
        console.log("add new item:" + val);
        this.items.push(val);
      }
    
      onlyNewlyAddedItems(val : string) {
        console.log("onlyNewlyAddedItems:" + val);
      }
    }
    

    应用程序组件.html :

    <h1 #test = customdirective appItemDetails [item]="currentItem">{{currentItem}}  item</h1>
    <label>Add an item: <input #newItem></label>
    <button (click) = addNewItem(newItem.value)>add new item</button>
    <h1 (newItemValue) = onlyNewlyAddedItems($event)></h1>
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   Ramanathan Chockalingam    5 年前

    要清除错误,

    在onlyNewlyAddedItems方法中,您需要字符串,但您要从模板传递$event。请尝试以下代码。

    <h1 #test = customdirective appItemDetails [item]="currentItem">{{currentItem}}  item</h1>
    <label>Add an item: <input #newItem></label>
    <button (click) = addNewItem(newItem.value)>add new item</button>
    <h1 (newItemValue) = onlyNewlyAddedItems(newItem.value)></h1>
    
    

        2
  •  0
  •   iwontcode    5 年前

    看看这个 StackBlitz 演示。 在这个示例中,您可以看到,当您从一个单独的子组件发出值时,您的代码可以工作。

    推荐文章