Angular `<router

编程入门 行业动态 更新时间:2024-10-23 15:22:32
本文介绍了Angular `<router-outlet>` 显示模板两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 angular4 并尝试创建路由器链接.路由器链接有效,但会显示模板两次.

I'm using angular4 and trying to create a router link. The router link works but displays the template twice.

以下是我在组件中的代码:

Below is my code in the component:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  template: `
  <h1>Contacts App</h1>
    <ul>
      <li><a [routerLink]="['/facebook/top']">Contact List</a></li>
    </ul>
    <router-outlet></router-outlet>
    `
})
export class AppComponent {
    constructor(
        private route: ActivatedRoute,
        private router: Router,
    ){ }

    gotoDetail(): void {
        this.router.navigate(['facebook/top']);
    }
}

我的路线:

const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'facebook/top',  component: CommentComponent },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

推荐答案

你的默认路由指向 AppComponent,所以你的路由渲染了 中的 AppComponent应用组件.

Your default route points to AppComponent, so your route is rendering the AppComponent inside the AppComponent.

为此创建一个 DashboardComponentHomeComponent.然后做:

Create a DashboardComponent or HomeComponent for this. And then do:

{ path: '', component: DashboardComponent }

更新 1:

正如@GünterZöchbauer 提到的,我们应该添加 pathMatch: 'full' 用于没有孩子的空路径".

As @GünterZöchbauer mentioned, we should add pathMatch: 'full' for "an empty path route with no children".

所以我们可以使用 AppComponent 方法(查看 Günter 的回答):

So we can go with the AppComponent approach (check Günter's answer):

{ path: '', component: AppComponent, pathMatch: 'full' }

或者,我在上面的回答中提到的 DashboardComponent 方法.

Or, the DashboardComponent approach as I stated above in my answer.

这篇关于Angular `&lt;router-outlet&gt;` 显示模板两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 11:53:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023591.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:amp   Angular   router   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!