为何在index.html中重复<app-root>标签无效果?
为什么多次写入
<app-root>只显示一个Hello World? 这其实是Angular框架的默认设计逻辑导致的哦~
当你启动Angular应用时,框架会在DOM中寻找第一个匹配根组件选择器(也就是<app-root>)的元素,然后把应用实例挂载到这个元素上。剩下的<app-root>标签会被完全忽略,因为Angular的启动机制只负责初始化一个根应用实例,不会处理多个同名的根组件标签。
解决办法
如果你想要显示多个Hello World实例,有两种常见的方案:
方案1:在根组件模板内重复渲染(推荐)
这是最符合Angular开发习惯的方式,只需要在app.component.html里直接重复你的内容:
<!-- app.component.html --> <h1>Hello World</h1> <h1>Hello World</h1> <h1>Hello World</h1>
然后index.html里只保留一个<app-root></app-root>标签即可,这样浏览器就会显示三个Hello World了。
方案2:创建多个根组件并分别引导
如果你确实需要多个独立的根组件实例,可以按以下步骤操作:
- 创建新的根组件:比如新增一个
AppRoot2Component
// app-root-2.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root-2', template: `<h1>Hello World 2</h1>` }) export class AppRoot2Component {}
- 在模块中声明组件:在
app.module.ts里把新组件加入declarations数组
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AppRoot2Component } from './app-root-2.component'; @NgModule({ declarations: [ AppComponent, AppRoot2Component ], imports: [BrowserModule], providers: [] }) export class AppModule { }
- 引导多个组件实例:修改
main.ts,分别引导每个根组件
// main.ts import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { AppRoot2Component } from './app/app-root-2.component'; // 先引导第一个根组件 platformBrowserDynamic().bootstrapModule(AppModule) .then(() => { // 再引导第二个根组件到对应的DOM元素 return platformBrowserDynamic().bootstrapComponent(AppRoot2Component); }) .catch(err => console.error(err));
- 在index.html中添加多个根组件标签
<!-- index.html --> <app-root></app-root> <app-root-2></app-root-2>
这样就能在页面上看到两个独立的Hello World实例了。
内容的提问来源于stack exchange,提问作者codingsplash
相关产品推荐
相关产品推荐

