【问题标题】:Why i can't go on the route of the child component?为什么我不能走子组件的路线?
【发布时间】:2019-03-18 11:06:23
【问题描述】:

我有以下项目结构:GalleryModuleModule 有一个父组件GalleryComponent,其中有两个子组件:GalleryAddComponentGalleryItemComponent。当我想从组件GalleryComponent切换到组件GalleryAddComponent时,地址栏中的地址发生了变化,但是父组件并没有消失,也没有发生到子组件的转换。帮助了解问题是什么以及如何解决此问题。

GalleryRoutingModule:

const galleryRoutes: Routes = [
    {
        path: 'gallery',
        component: GalleryComponent,
        children: [
            {path: 'gallery-add', component: GalleryAddComponent},
            {path: 'galleryItem/:id', component: GalleryItemComponent},
        ]
    }
];

@NgModule({
    imports: [
        CommonModule,
        RouterModule.forChild(galleryRoutes)
    ],
    exports: [RouterModule],
})

GalleryComponent 的模板:

                <a routerLink="gallery-add" class="btn btn-outline-success tog">
                    Add New Post
                </a>
        <a [routerLink]="['./galleryItem', pic.id]">
            <img [src]="pic.url" alt="test" class="img-responsive">
            <p class="lead"><span>{{pic.id}}:</span>{{pic.title}}</p>
        </a>

【问题讨论】:

  • 你为什么用'./galleryItem'
  • 作为子路由,GaleryAddComponent 通常会添加到GalleryComponent 内的router-outlet。如果要替换 GalleryComponent,请将其添加到该 children 数组中,并使用空路径
  • 当我使用“galleryItem”时没有任何变化
  • @user184994 thx,现在我看到了 add 和 item 组件,你能不能更详细地告诉我当我切换到“GalleryAddComponent”或“GalleryitemComponent”时如何隐藏“GalleryComponent”
  • @IgorShvets 你能在 StackBlitz 中创建一个基本的复制品吗?组件不需要功能,只需路由即可。然后我可以编辑它来告诉你我的意思

标签: javascript angular typescript routing angular-ui-router


【解决方案1】:

你需要有一个不同的组件来保存&lt;router-outlet&gt;&lt;/router-outlet&gt;。如果路径是'',你可以在那里显示GalleryComponent。您可以通过GalleryComponent 获得其他两个组件的链接:GalleryItemComponent, GalleryAddComponent。这样,当您单击图库组件中的链接时,它将被另一个组件替换。

在 stackblitz https://angular-hbb4qt.stackblitz.io 上创建了一个示例

【讨论】:

  • 更新了 stackblitz 链接
  • 谢谢,但我需要“GalleryComponent”是父组件,因为我在条件下禁止访问它,而在“AppComponent”这就是我的意思(我的一些项目):@ 987654322@
  • 你可以在appcomponent中使用同样的[canActivate]保护
猜你喜欢
  • 1970-01-01
  • 2016-06-18
  • 2015-07-01
  • 1970-01-01
  • 2016-05-15
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多