Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在单击按钮时将绑定变量的值传递给模板中的方法_Javascript_Node.js_Angular_Typescript_Angular Directive - Fatal编程技术网

Javascript 如何在单击按钮时将绑定变量的值传递给模板中的方法

Javascript 如何在单击按钮时将绑定变量的值传递给模板中的方法,javascript,node.js,angular,typescript,angular-directive,Javascript,Node.js,Angular,Typescript,Angular Directive,我正在学习如何使用@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.

我正在学习如何使用@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.
app.coponent.html

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");
  }
}
import { Directive, Input, Output, EventEmitter } from '@angular/core';

@Directive({
  selector: '[appItemDetails]'
})
export class ItemDetailsDirective {

  @Input() item : string = "";

  constructor() { }
  ngOnInit() {
    console.log("ngOnInit->:" + this.item)
  }

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

您可以按如下方式添加导出:

@Directive({
  selector: '[appItemDetails]'
  exportAs: 'customdirective',
})
export class ItemDetailsDirective {
....
}
在html中,您可以添加对指令的引用并获取绑定值:

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

is addNewItem应该是addNewItem(currentItem)@Pradeep是的,我想在单击按钮时执行此操作…这就是为什么我想知道如何从模板访问项目为什么要执行item.value,可以执行绑定值为的currentItempresent@Pradeep因为我想学习如何使用它,既然您已经将
currentItem
绑定到
item
,您就不能使用:
@Directive({
  selector: '[appItemDetails]'
  exportAs: 'customdirective',
})
export class ItemDetailsDirective {
....
}
<h1 #test="customdirective" appItemDetails [item]="currentItem">{{currentItem}}</h1>
<button (click) = addNewItem(test.item)></button>