Angular中使用app-home选择器为何导致路由页面显示异常?
问题场景
我在Angular项目中创建了两个子组件:
- 子组件1选择器为
app-home,HTML内容为<p>child 1 here</p>; - 子组件2选择器为
app-plans,HTML内容为<p>Child 2 here</p>。
初始将app.component.html设置为<app-home></app-home>,路由配置如下:
const routes: Routes = [ {path: 'plans', component: PlansComponent}, {home: 'home', component: HomeComponent} ]
此时访问localhost:4200/plans,页面同时显示“child 1 here”和“Child 2 here”,但期望仅显示“Child 2 here”。当把app.component.html改为<router-outlet></router-outlet>后,访问该路由则仅显示“Child 2 here”,符合预期。
请问使用app-home选择器的配置存在什么问题?为何会出现这种异常显示?
问题原因及解决方法
核心问题点
根组件模板的固定渲染逻辑
AppComponent是Angular应用的根组件,它的模板内容是全局固定渲染的——只要你在app.component.html里写了<app-home></app-home>,不管当前路由是什么,这个组件都会一直显示在页面上,不会被路由替换。路由组件的默认渲染行为
Angular路由匹配到目标组件后,必须通过<router-outlet>指定渲染位置。如果根模板里没有<router-outlet>,Angular会把路由匹配到的组件追加到根组件已有的内容后面,所以访问/plans时,app-home的内容保留,PlansComponent的内容也被加上,就出现了两者同时显示的情况。路由配置的语法错误
你写的{home: 'home', component: HomeComponent}是无效配置——Angular路由配置里没有home这个属性,正确的写法应该是用path字段,比如{path: 'home', component: HomeComponent}或者{path: '', component: HomeComponent}(根路径匹配)。这个错误会导致HomeComponent无法通过路由正常渲染,但不影响plans路由的匹配。
正确配置方式
- 把
app.component.html的内容改成仅保留<router-outlet></router-outlet>,让所有页面内容都通过路由控制渲染; - 修正路由配置的语法错误:
const routes: Routes = [ {path: '', component: HomeComponent}, // 访问根路径时显示HomeComponent {path: 'plans', component: PlansComponent}, ];
这样配置后,访问不同路由时,只有匹配到的组件会渲染在<router-outlet>的位置,根组件不会额外渲染固定内容,就不会出现多组件同时显示的问题了。
内容的提问来源于stack exchange,提问作者victor

