簡體   English   中英

如何使用Angular 2 Router導航到頁面的特定部分?

[英]How to navigate to a specific part of the page with the Angular 2 Router?

我正在嘗試導航到Angular 2組件中的特定元素。 從我閱讀的文檔中可以看出,片段與NavigationExtras對象一起使用。 當我要在同一頁面中導航時,我不確定如何執行此操作。

問題的另一部分是我要導航到的頁面部分通過* ngFor加載,並使用我要導航的id創建div元素。

在將其加載到DOM中之前,我可能會嘗試導航至頁面的該部分。 我在它周圍設置了一個超時,以查看是否有幫助,但是到目前為止還沒有成功。

我在屬性頁面上,並嘗試導航到頁面內的另一部分。 您可以在HTML中看到我在需要導航到的div上設置id的位置。

  if (sessionStorage['destinationProperty'] !== undefined) { let navigationExtras: NavigationExtras = { fragment: sessionStorage.getItem('destinationProperty') } window.setTimeout(() => { this._router.navigate(['/properties'], navigationExtras); }, 1000); } 
  <div class="row" *ngFor="let p of properties"> <div class="col-md-12"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6" id="{{p.id}}"> <table> <tr> <td rowspan="3"><img [src]="getImgPath(p)" /></td> <td class="title" (click)="destination(p)">{{p.name}}</td> </tr> <tr> <td class="summary">{{p.summary}}</td> </tr> <tr> <td><span class="mapLink" (click)="mapview(p)">view on map <i class="fa fa-map-o" aria-hidden="true"></i></span></td> </tr> </table> </div> <div class="col-md-3"></div> </div> </div> </div> 

  • 在Angular2應用中,您可以為某些組件設置路由器。

  • 每個組件可以具有自己的其他組件路由器,依此類推。

因此,實際上您的主路由器需要一個子路由器。
這是Angular2文檔中的示例 ,說明了它們如何處理子路由器:
主路由器

import { ModuleWithProviders }  from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: '', redirectTo: 'contact', pathMatch: 'full'},
  { path: 'crisis', loadChildren: 'app/crisis/crisis.module#CrisisModule' },
  { path: 'heroes', loadChildren: 'app/hero/hero.module#HeroModule' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

子路由器

    import { ModuleWithProviders } from '@angular/core';
    import { Routes,
             RouterModule } from '@angular/router';

    import { HeroComponent }       from './hero.component';
    import { HeroListComponent }   from './hero-list.component';
    import { HeroDetailComponent } from './hero-detail.component';

    const routes: Routes = [
      { path: '',
        component: HeroComponent,
        children: [
          { path: '',    component: HeroListComponent },
          { path: ':id', component: HeroDetailComponent }
        ]
      }
    ];

export const routing: ModuleWithProviders = RouterModule.forChild(routes);

鏈接到完整示例:
Angular2路由器延遲加載
Angular2完整工作的插件,用於路由器的延遲加載

暫無
暫無

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

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