簡體   English   中英

Angular 2 路由中斷(單擊)處理程序更改檢測

[英]Angular 2 routing breaks (click) handler change detection

“初始化.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>
 

這是我的流程的基本實現。 我最初是路由到我的 HomeFeedComponent,但是一旦我在我的初始路由上到達那里。 即使 display 等於 true (我什至從組件控制台記錄它)我的前端也不會呈現 class 'Active' 除非我添加this.ChangeDetectorRef.detectChanges(); clickyClick

但是,當我在默認路由之后路由回該組件時,無需detectChanges

問題:所以我很想知道我在這里做錯了什么,為什么我必須在最初路由時手動觸發detectChanges 這是 Angular 錯誤還是我的邏輯有問題?

提前致謝!

看起來這個修復相對簡單! 由於某種原因,當我們router.navigate時,我們會丟失更改檢測。 以下是將組件放回Angular尋找變化的區域的方法。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM