I am learing how to make binding between the parent and the child using @Input, @Output and EventEmitter decorators. in the html section posted below
<h1 appItemDetails [item]="currentItem">{{currentItem}}</h1>
currentItem has value equal to "TV". and i pass this value to the binding variable item.
i added console.log in ngOnInit that prints the value of item to make sure that the binding from the parent to the child is working as suppose to be.
in
<button (click) = addNewItem(item.value)></button>
in this button tag i am trying to pass the value of the binding variable item to the method addNewItem() as a parameter. For the method addNewItem() it exists in the component and it should be invoked with the right parameter which is the value of the binding variable item
when i compile the App i revceive the error posted below. please let me know how to pass the value of the binding variable to a method on button clicked
error
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>
you can add exportAs like below:
@Directive({
selector: '[appItemDetails]'
exportAs: 'customdirective',
})
export class ItemDetailsDirective {
....
}
and in your html, you can add a reference to directive and get the binded value:
<h1 #test="customdirective" appItemDetails [item]="currentItem">{{currentItem}}</h1>
<button (click) = addNewItem(test.item)></button>