英文:
Child component is displayed under another child component
问题
Child #1 组件:
selector: 'app-home'
Child #2 组件:
selector: 'app-plans'
Child #1 HTML:
<p>child 1 here</p>
Child #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 },
{ path: 'home', component: HomeComponent }
]
在浏览器中访问 localhost:4200/plans 显示:
child 1 here
child 2 here
如果我将 app.component.html 更改为:
<router-outlet></router-outlet>
localhost:4200/plans 显示:
child 2 here
为什么在 app.component.html 中使用 'app-home' 选择器有问题?为什么在 localhost:4200/plans 中显示 "child 1 here"?(我期望只显示 "child 2 here"。)
英文:
Child #1 Component:
selector: 'app-home'
child #2 component:
selector: 'app-plans'
child #1 html:
<p>child 1 here</p>
child #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}
]
in browser localhost:4200/plans displays:
child 1 here
child 2 here
if I change app.component.html to:
<router-outlet></router-outlet>
localhost:4200/plans displays:
child 2 here
What's wrong with using 'app-home' selector in app.component.html? why is it showing "child 1 here" in localhost:4200/plans? (i am expecting "child 2 here" only.)
<router-outlet></router-outlet> shows results I expected, but I don't understand why <app-home></app-home> doesn't work as I expected.
答案1
得分: 0
如果你想使用路由策略,需要在你的主组件中插入RouterOutlet指令,就像你这样做的<router-outlet></router-outlet>
一样。RouterOutlet指令是一个占位符,Angular会根据活动路由动态填充适当的内容。
所以,如果你有一个活动路由,比如localhost:4200/plans
,并且想要看到在路由定义中配置的组件PlansComponent
,那么你应该在你的应用组件中只使用<router-outlet></router-outlet>
。
在你的应用组件中使用<app-home></app-home>
只是静态地渲染HomeComponent
,与你的路由实现无关。
英文:
If you want to use the router strategy you need to insert the RouterOutlet directive in your main component like you did <router-outlet></router-outlet>
. The RouterOutlet directive is a placeholder that angular fills dynamically with the appropriate content based on the active route.
So if you have an active route like localhost:4200/plans
and want to see only the component configured in the route definition PlansComponent
, then you should just use <router-outlet></router-outlet>
in your app component.
With <app-home></app-home>
in your app component you are just statically rendering the HomeComponent
and nothing to do with your routing implementation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论