子组件显示在另一个子组件下

Child component is displayed under another child component

提问人:victor 提问时间:6/26/2023 最后编辑:victor 更新时间:6/26/2023 访问量:31

问:

子 #1 组件: 选择器: 'app-home'

子 #2 组件: 选择器: 'app-plans'

子 #1 html:

    <p>child 1 here</p>

子 #2 HTML:

    <p>Child 2 here</p>

app.component.html:

<app-home></app-home>

app-routing.module.ts:

    const routes: Routes = [
    {path: 'plans', component: PlansComponent},
    {home: 'home', component: HomeComponent} 
    ]

在浏览器 localhost:4200/plans 中显示: 孩子 1 在这里 孩子 2 在这里

如果我将app.component.html更改为:

    <router-outlet></router-outlet>

localhost:4200/plans 显示: 孩子 2 在这里

在app.component.html中使用“app-home”选择器有什么问题?为什么它在 localhost:4200/plans 中显示“child 1 here”?(我只期待“孩子 2 在这里”。

显示了我预期的结果,但我不明白为什么没有像我预期的那样工作。

角度 选择器 路由器插座

评论

0赞 Ajay Managaon 6/26/2023
请提供可重现的源代码。

答:

0赞 Mehyar Sawas 6/26/2023 #1

如果要使用路由器策略,则需要像执行以下操作一样在主组件中插入 RouterOutlet 指令。RouterOutlet 指令是一个占位符,它根据活动路由动态填充适当的内容。<router-outlet></router-outlet>

因此,如果您有一个活动路由,例如并且只想查看在路由定义中配置的组件,那么您应该只在应用程序组件中使用。localhost:4200/plansPlansComponent<router-outlet></router-outlet>

在应用组件中,您只是静态渲染,与路由实现无关。<app-home></app-home>HomeComponent