I have an Angular component using change detection on push. The component has an input that is modified by the component when the route is updated. If I assign the input to a new reference and modify it, the value in the template is not updated. I thought as long as you assigned a new object the change would be detected, but it is not unless I call detectChanges() on the ChangeDetectorRef.
@Component({
selector: 'app-nav-links',
templateUrl: './nav-links.component.html',
styleUrls: ['./nav-links.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NavLinksComponent implements OnInit {
@Input() links: Link[] = [];
private currentPath: string;
constructor(private router: Router,
private route: ActivatedRoute,
private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.router.events.subscribe(() => {
this.updateActiveRoute();
});
}
private updateActiveRoute() {
this.currentPath = this.route.snapshot.children[0].routeConfig.path;
this.links = [...this.links].map(link => {
link.active = link.url === this.currentPath;
return link;
});
// Why is this required if I am already using the spread operator?
this.cdr.detectChanges();
}
}