No, events triggered in the parent component cannot directly cause change detection in a child component with the `OnPush` change detection strategy in Angular. The `OnPush` strategy only triggers change detection in a component when one of the following conditions is met:
1. The input properties of the component change.
2. An event emitted by the component itself or one of its child components is received.
To demonstrate this, let's consider an example with a parent component and a child component, both using the `OnPush` change detection strategy:
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<button (click)="triggerEvent()">Trigger Event</button>
<app-child [inputproperty]="inputProperty"></app-child>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent {
inputProperty: string = 'Initial value';
triggerEvent() {
// Event triggered in the parent component
console.log('Event triggered in parent component');
}
}
// child.component.ts
import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{ inputProperty }}
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() inputProperty: string;
}
In this example, the `ParentComponent` has a button that triggers the `triggerEvent()` method. However, since the `ParentComponent` and `ChildComponent` both use the `OnPush` change detection strategy, the event triggered in the parent component will not directly trigger change detection in the child component.
To propagate changes from the parent to the child component, you would need to update an input property of the child component. For example, you can modify the `triggerEvent()` method in the `ParentComponent` as follows:
triggerEvent() {
this.inputProperty = 'New value'; // Update input property of child component
}
By updating the input property value, Angular's change detection mechanism will detect the change and trigger change detection within the child component with the `OnPush` strategy. This will update the child component's view accordingly.
Conclusion :
To summarize, events triggered in the parent component do not directly cause change detection in a child component with the `OnPush` strategy. However, you can indirectly trigger change detection by updating an input property of the child component from the parent component.
Therefore, if an event is triggered in the parent component, it will not automatically trigger change detection in a child component with the `OnPush` strategy. This behavior is intentional to optimize performance by reducing unnecessary change detection cycles.