Performance: ngOnChanges for input changes
This affects how quickly Angular detects and responds to changes in component inputs, impacting interaction responsiveness and rendering updates.
ngOnChanges(changes: SimpleChanges) {
if (changes['importantInput'] && !changes['importantInput'].isFirstChange()) {
// Minimal logic only when important input changes
this.updateData();
}
}ngOnChanges(changes: SimpleChanges) {
// Heavy logic or DOM manipulation on every input change
for (const propName in changes) {
if (changes.hasOwnProperty(propName)) {
// Expensive operation
this.updateDomOrData();
}
}
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy logic on all input changes | Multiple DOM updates | Multiple reflows per change | High paint cost | [X] Bad |
| Selective logic on specific inputs | Minimal DOM updates | Single reflow per relevant change | Low paint cost | [OK] Good |
ngOnChanges lifecycle hook in Angular?ngOnChanges hook is called when Angular detects changes to input properties of a component.ngOnInit initialize data, but ngOnChanges specifically reacts to input changes.ngOnChanges in an Angular component?ngOnChanges method receives a parameter of type SimpleChanges which holds the changes.SimpleChanges, not other types.export class MyComponent implements OnChanges {
@Input() count = 0;
changesLog: string[] = [];
ngOnChanges(changes: SimpleChanges) {
if (changes['count']) {
this.changesLog.push(`Count changed from ${changes['count'].previousValue} to ${changes['count'].currentValue}`);
}
}
}changesLog after the input count changes from 5 to 10?changes['count'] object has previousValue and currentValue reflecting old and new input values.count changes from 5 to 10, previousValue is 5 and currentValue is 10, so the string is pushed accordingly.ngOnChanges:export class TestComponent implements OnChanges {
@Input() data: string;
ngOnChanges() {
console.log(this.data);
}
}ngOnChanges method must accept a parameter of type SimpleChanges to receive input changes.resetFlag changes from false to true. Which ngOnChanges implementation correctly achieves this?export class CounterComponent implements OnChanges {
@Input() resetFlag = false;
@Input() otherValue: number = 0;
counter = 10;
ngOnChanges(changes: SimpleChanges) {
// Which option resets counter correctly?
}
}resetFlag changed and its new value is true.Pass the test and this pattern moves unknown