在下面的代码中,我想使用事件发射器来调用方法“onlyNewAddedItems”。 我定义了 eventemitter 实例和发出事件的方法,如下所示
@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”。
AppComponent.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);
}
}
app.component.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>
答案 0 :(得分:1)
要清除错误,
在 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>
<块引用>
但是在组件内部监听是行不通的。因为这些 装饰器(输入和输出)用于从组件外部进行通信。
答案 1 :(得分:0)
查看此 StackBlitz 演示。 事件发射器用于将数据传递给父组件。 在示例中,您可以看到当您从单独的子组件发出值时,您的代码可以正常工作。