Currently, I am exploring the process of creating binding between a parent and child component using @Input, @Output, and EventEmitter decorators. Below is an example code snippet demonstrating this:
@Output() newItemValue = new EventEmitter<string>();
In this code, I have defined an EventEmitter that will trigger when the method `addNewItem` is called with a string parameter. Inside the `addNewItem` method, the value is emitted like so:
this.newItemValue.emit(val);
To establish a binding with `this.newItemValue`, I made some modifications in the HTML file as shown below:
<button appItemDetails (click) = addNewItem(newItem.value)>add new item</button>
<p (newItemValue)="onlyNewlyAddedItems($event)"></p>
Upon compiling the application, an error was encountered which is outlined below. Kindly share how to properly bind to `this.newItemValue` from the template.
Error:
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);
}
}
item-details.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>