【发布时间】:2018-05-02 23:34:55
【问题描述】:
我有一个使用推送更改检测的 Angular 组件。 组件有一个输入,当路由更新时组件会修改该输入。 如果我将输入分配给新引用并对其进行修改,则模板中的值不会更新。我以为只要您分配了一个新对象,就会检测到更改,但除非我在 ChangeDetectorRef 上调用 detectChanges()。
@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();
}
}
【问题讨论】:
标签: angular