On Changes in Angular
This example shows how to react only when a parent input changes, while skipping the automatic first assignment that happens when the component initialises.
Published: 6/6/2024React to changes from the parent input#
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-demo',
template: `Current value: {{ value }}`
})
export class DemoComponent implements OnChanges {
@Input() value!: string;
ngOnChanges(changes: SimpleChanges): void {
if (changes['value'].firstChange) {
console.log('Skipping change on component init:', changes['value'].currentValue);
} else {
console.log('Value updated to:', changes['value'].currentValue);
}
}
}
Parent usage#
<app-demo [value]="someText"></app-demo>
<button (click)="someText = 'Updated!'">Update Value</button>