Angular:从组件重定向到组件

Sri*_*mar -1 angular-ui-router angular

在我尝试学习角度路由和导航时,我注意到了这个导航部分。

我的角度组件结构:

AppComponent
    -LandingPage
    -WhatEver1
     -Home
     -Price
     -Sales
    -WhatEver2
     -Blog
     -ContactUs
Run Code Online (Sandbox Code Playgroud)

我的路线:

const appRoutes: Routes = [
  {path: '', component: LandingPageComponent},
  {path: 'whatever-1', component: WhateverComponent},
  {path: 'whatever-2', component: Whatever2Component}
];
Run Code Online (Sandbox Code Playgroud)

我尝试在登陆页面上有两个按钮,以便每个按钮都可以导航到其中一个组件。

登陆页面的 HTML 部分:

<div class="row">
    <button class="btn btn-primary" (click)="redirectToTravelLife()">Travel Life</button>
    <button class="btn btn-warning" (click)="redirectToSoftwareLife()">Software Life</button>
  </div>

  <div class="row">
    <router-outlet></router-outlet>
  </div>
Run Code Online (Sandbox Code Playgroud)

打字稿代码:

constructor(private router: Router) {}

  redirectToSoftwareLife() {
      this.router.navigateByUrl('/whatever-1');
  }
  redirectToTravelLife() {
      this.router.navigateByUrl('/whatever-2');
  }
Run Code Online (Sandbox Code Playgroud)

导航正在进行,但按钮仍然存在。如何进行正确的导航,以便无论我重定向到什么组件,都只显示该组件及其子组件。

小智 5

问题出在您的着陆页 html 组件上。您有该页面的静态部分的按钮和动态的路由器出口。Router-outlet 充当小丑,这意味着在您的情况下,当您单击其中一个按钮时,您的按钮将始终可见,并且只有组件的 router-outlet 部分会动态更改。

您需要有带有按钮的独立组件(我们称之为 LandingPageComponent)和 2 个独立的组件(Whathever1Component 和 Whathever2Component)。

您的路由器模块应该具有如下所示的路由:

const routes: Routes = [
    {path: 'landingpage', component: LandingPageComponent},
    {path: 'whatever-1', component: Whatever1Component},
    {path: 'whatever-2', component: Whatever2Component}
];
Run Code Online (Sandbox Code Playgroud)

现在您将拥有没有路由器出口的登陆页面,因此当您单击按钮时,您将被重定向到WhateverComponent 或Whatever2Component,并且当然不会呈现按钮!

希望这可以帮助!

编辑:

关于您的评论(“我应该在哪里保留我的应用程序登陆页面”),这就是您需要的:您的应用程序组件应该有路由器出口。在该路由器出口内将呈现应用程序的其他部分(登陆页面,whatever1,whatever2,...),并且您将需要拥有我已经编写的路由结构。您不需要将应用程序登陆页面放在任何地方,您已经通过路线将其包含在内。因此,当您转到路线 /landingpage 时,该组件将被渲染。例子:

应用程序组件.html:

<div>
    <router-outlet></router-outlet>
</div>
Run Code Online (Sandbox Code Playgroud)

应用程序路由.module.ts:

...
const routes: Routes = [
    {path: '', redirectTo: 'landingpage', pathMatch: 'full'},
    {path: 'landingpage', component: LandingPageComponent},
    {path: 'whatever-1', component: Whatever1Component,
    children: [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: HomeComponent},
        { path: 'price', component: PriceComponent },
        { path: 'sales', component: SalesComponent }
    ]},
    {path: 'whatever-2', component: Whatever2Component,
    children: [
        { path: '', redirectTo: 'blog', pathMatch: 'full' },
        { path: 'blog', component: BlogComponent},
        { path: 'contactus', component: ContactComponent }
    ]}
   ];
...
Run Code Online (Sandbox Code Playgroud)