Here is my app.component.ts code:
import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core';
import {Counter } from './counter'
@Component({
selector: 'my-app',
template: `
<custom-counter [(counter)]="counterArray" (counterChange)="myValueChange($event);"></custom-counter>
<p><code>counterValue = {{counterValue}}</code></p>
<hr>
`
})
export class AppComponent implements OnChanges{
counterArray:Counter[]
counterValue = 5;
constructor(){
this.counterArray=[{id:0,value:0},{id:1,value:1}]
}
myValueChange(event:Counter[]) {
console.log(event);
}
}
This is my counter.ts file:
export class Counter {
id: number;
value: number;
}
And here is the custom-counter component:
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Counter } from './counter';
@Component({
selector: 'custom-counter',
template: `
First counter
<button (click)="decrement()">-</button>
<span>{{this.counter[1].value}}</span>
<button (click)="increment()">+</button>
`
})
export class CustomCounterComponent {
@Input() counter : Counter[];
@Output() counterChange = new EventEmitter();
decrement() {
this.counter[1].value--;
this.counterChange.emit({
value: this.counter
})
}
increment() {
this.counter[1].value++;
this.counterChange.emit({
value: this.counter
})
}
}
My original plan was to notify the parent component when a button is pressed in the child component and print something in console. However, I encountered an error message:
"Error in ./CustomCounterComponent class CustomCounterComponent - inline template:3:10 caused by: Cannot read property 'value' of undefined"
I understand that this error indicates something is undefined even though everything is passed correctly.
If I remove the lines with 'emit', no error occurs, but then there are no notifications sent to the parent component.