我正在学习如何使用@Input、@Output 和 EventEmitter 装饰器在父子之间进行绑定。在下面的代码中
@Output() newItemValue = new EventEmitter<string>();
我创建了一个事件发射器,它会在对字符串参数调用方法 addNewItem 时发出一个值。在我调用的 addNewItem 方法的主体中
this.newItemValue.emit(val);
我想绑定 this.newItemValue,所以我在 html 文件中做了以下操作
<button appItemDetails (click) = addNewItem(newItem.value)>add new item</button>
<p (newItemValue)="onlyNewlyAddedItems($event)"></p>
但是当我编译应用程序时,我收到了下面发布的错误。请让我知道如何从模板中绑定 this.newItemValue
错误
Failed to compile.
src/app/app.component.html:4:40 - error TS2345: Argument of type 'Event' is not assignable to parameter of type 'string'.
4 <p (newItemValue)="onlyNewlyAddedItems($event)"></p>
~~~~~~
src/app/app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
app.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);
console.log("add new item:" + this.items);
}
onlyNewlyAddedItems(val : string) {
console.log("onlyNewlyAddedItems:" + val);
}
}
项目详细信息.directive.ts:
import { Directive, Input, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appItemDetails]',
exportAs: 'customdirective'
})
export class ItemDetailsDirective {
@Input() item : string = "";
constructor() { }
ngOnInit() {
console.log("ngOnInit->:" + this.item)
}
ngOnChange() {}
}
app.coponent.html:
<h1 #test = customdirective appItemDetails [item]="currentItem">{{currentItem}} item</h1>
<label>Add an item: <input #newItem></label>
<button appItemDetails (click) = addNewItem(newItem.value)>add new item</button>
<p (newItemValue)="onlyNewlyAddedItems($event)"></p>