i am trying to use ngOnChanges in order to update a string(even or odd) after another variable(counter) changes but the value of message stays '' and doesnt update when the counter changes.
export class CounterComponent{
counter: number = 0;
message: string = '';
ngOnChanges(changes: SimpleChanges) {
if (changes['counter']) {
this.message = this.counter % 2 === 0 ? 'Even' : 'Odd';
}
}
increment() {
this.counter++;
}
decrement() {
this.counter--;
}
}
<div>
<p>Counter: {{ counter }}</p>
<p>Message: {{ message }}</p>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
</div>
Thank you for your time.
I have tried **all solutions ** i could find but nothing works, i have tried these : 1.
@input counter: number = 0;
ngOnChanges(changes: any) {
if (changes.counter) {
this.message = this.counter % 2 === 0 ? 'Even' : 'Odd';
}
}
ngOnChanges(changes: any) {
if (changes.counter.currentValue) {
this.message = this.counter % 2 === 0 ? 'Even' : 'Odd';
}
}
ngOnChanges(changes: SimpleChanges) {
if (changes['counter'].currentValue) {
this.message = this.counter % 2 === 0 ? 'Even' : 'Odd';
}
}