【问题标题】:How to pass value of a binding variable to a method in the template on button clicked如何在单击按钮时将绑定变量的值传递给模板中的方法
【发布时间】: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,您就不能使用:&lt;button (click) = addNewItem(currentItem)&gt;&lt;/button&gt; 吗?

标签: javascript node.js angular typescript angular-directive


【解决方案1】:

您可以添加导出如下:

@Directive({
  selector: '[appItemDetails]'
  exportAs: 'customdirective',
})
export class ItemDetailsDirective {
....
}

在你的 html 中,你可以添加对指令的引用并获取绑定的值:

<h1 #test="customdirective" appItemDetails [item]="currentItem">{{currentItem}}</h1>
<button (click) = addNewItem(test.item)></button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多