Angular 2 routing breaks (click) handler change detection

247 views Asked by At

"initialize.ts"

platform.bootstrapModule(HomeModule);
 

"home.module.ts"

const appRoutes: Routes = [    
     { path: 'home', component: HomeFeedComponent }, 
]

@NgModule({
    bootstrap: [
        HomeAppComponent,
        HomeFeedComponent
    ],

export class HomeModule { constructor() { bootstrapComponents(UnrelatedComponent) } }

"home-app.component.ts"

export class HomeAppComponent {
     public defaultUrl: string;
     this.defaultUrl = '/' + 'home';
     this.router.navigateByUrl(this.defaultUrl);
 }

"home-feed.component.ts"

@Component({
    selector: 'home-feed',
    template: '../templates/home-feed.html'
})

export class HomeFeedComponent implements NgOnInit {
   public display = false;

   constructor() {}

   public ngOnInit(): void {}

   public clickyClick(): void { 
      this.display = true;
   }
}

"home-feed.html"

    <li class="message-tab"><a (click)="clickyClick()"
        [ngClass]="{ 'active': display }">Message</a>
    </li>
 

Here is a bare bones implementation of my process. I am initially routing to my HomeFeedComponent, however once I get there on my initial route. Even though display is equal to true (I even console log this from the component) my front end does not render the class 'Active' unless I add this.ChangeDetectorRef.detectChanges(); to clickyClick.

However when I route back to this component after my default route this works without the need for detectChanges.

Question: So I'd love to know what I am doing wrong here, why do I have to manually trigger detectChanges when initially routing? Is this an Angular bug or is my logic wonky?

Thanks in advance!

1

There are 1 answers

0
wsoccorsi On BEST ANSWER

Looks like this fix was relatively simple! For some reason when we router.navigate we lose change detection. The following is a way to put the component back in the area Angular looks for changes.

this.zone.run(() => {
      this.router.navigate(this.defaultUrl);
});

https://github.com/angular/angular/issues/23697