【发布时间】:2021-06-30 00:33:47
【问题描述】:
我正在学习如何使用 @Input、@Output 和 EventEmitter 装饰器在父子之间进行绑定。 在下面发布的 html 部分中
<h1 appItemDetails [item]="currentItem">{{currentItem}}</h1>
currentItem has value equal to "TV". and i pass this value to the binding variable item.
我在 ngOnInit 中添加了 console.log 来打印 item 的值,以确保从父级到子级的绑定正常工作。
在
<button (click) = addNewItem(item.value)></button>
在此按钮标记中,我试图将绑定变量 item 的值作为参数传递给方法 addNewItem()。 对于 addNewItem() 方法,它存在于组件中,应该使用正确的参数调用它,该参数是绑定变量 item 的值
当我编译应用程序时,我收到了下面发布的错误。 请让我知道如何将绑定变量的值传递给单击按钮上的方法
错误
TS2339: Property 'item' does not exist on type 'AppComponent'.
2 <button (click) = addNewItem(item.value)></button>
~~~~
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';
@Output() newItemValue = new EventEmitter<string>();
addNewItem(val : string) {
this.newItemValue.emit(val);
console.log("add new item");
}
}
item-details.directive.ts:
import { Directive, Input, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appItemDetails]'
})
export class ItemDetailsDirective {
@Input() item : string = "";
constructor() { }
ngOnInit() {
console.log("ngOnInit->:" + this.item)
}
}
app.coponent.html:
<h1 appItemDetails [item]="currentItem">{{currentItem}}</h1>
<button (click) = addNewItem(item.value)></button>
【问题讨论】:
-
is addNewItem 应该是 addNewItem(currentItem)
-
@Pradeep 是的,我想在单击按钮时这样做......这就是为什么我想知道如何从模板访问项目
-
为什么要做item.value,可以做绑定值所在的currentItem
-
@Pradeep 因为我想学习如何去做
-
既然您已经将
currentItem绑定到item,您就不能使用:<button (click) = addNewItem(currentItem)></button>吗?
标签: javascript node.js angular typescript angular-directive