I have parent component
@Component({
selector: 'parent',
template: '
<div *ngIf="!service.activeTab">DEFAULT</div>
<div *ngIf="service.activeTab">
<div (click)="service.resetActiveTab()">DEFAULT | </div>
<div>Active Tab</div>
</div>
<child></child>
',
styleUrl: './parent.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [MyService]
})
export class ParentComponent {
constructor(public service: MyService) {}
}
Child component
@Component({
selector: 'child',
template: '
<ng-container *ngIf="!service.activeTab">
<div *ngFor="let tab of service.tabs" (click)="setActiveTab(tab)"></div>
</ng-container>
<ng-container *ngIf="service.activeTab">{{service.activeTab.name}}</ng-container>
',
styleUrl: './child.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
constructor(public service: MyService) {}
setActiveTab(tab: ITab) {
this.service.setActiveTab(tab);
}
}
Service
@Injectable()
export class MyService {
activeTab: ITab|null = null;
tabs = [{id: 1, name: '1'}, {id: 2, name: '2'}];
resetActiveTab() {
this.activeTab = null;
}
setActiveTab(tab: ITab) {
this.activeTab = tab;
}
}
When I click in child component on tab setActiveTab function called. activeTab is being initialized as in child and parent component.
When I click in parant component on div resetActiveTab function called. activeTab is being initialized only in parent component. Child component activeTab has prev value. If click somewhere or do something than in child activeTab became null
If I remove OnPush strategy everything will be ok.
ChangeDetectorRef in service in resetActiveTab function doesn’t work. detectChanges doesn’t trigger child component.
Do you have any ideas?
I don’t understand why if I use one Service both components activeTab change only in parent component and doesn’t in child.