gpt4 book ai didi

angular - 为什么没有 的其他组件不会出现在 index.html 上?

转载 作者:行者123 更新时间:2023-12-04 14:18:20 24 4
gpt4 key购买 nike

我刚刚开始学习 Angular 并学习了一些教程。我的项目是由 Angular CLI 生成的。我在创建项目时生成的组件顶部生成了一个名为导航栏的新组件,我试图查看导航栏是否在启动时加载到我的 index.html 上。我的导航栏仅在 index.html 文件中有两个应用程序时才会显示,例如:

<body>
<app-root></app-root>
<app-navbar></app-navbar>
</body>

如果我像这样从 index.html 中删除 app-root:
<body>
<app-navbar></app-navbar>
</body>

我的导航栏应用程序不再显示。这与 app-root 组件有关吗?是不是因为它是一个根组件并且它必须一直包含在 index.html 中?

这是我的代码:

索引.html:
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
<app-navbar></app-navbar>
</body>

</html>

app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './component1/app.component';
import { NavbarComponent } from './navbar/navbar.component';

@NgModule({
declarations: [
AppComponent,
NavbarComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [
AppComponent,
NavbarComponent
]
})
export class AppModule { }

导航栏.component.ts:
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent {
constructor() {}

// tslint:disable-next-line: use-lifecycle-interface
ngOnInit() {

}
}

最佳答案

您必须将组件选择器放在 app.component.html 中:

<app-navbar></app-navbar>

<app-root> 标签是显示引导组件的位置(默认为 AppComponent )。通常你不需要超过 1 个引导组件,所以从 AppModule 的 bootstrap 中删除 NavbarComponent

在更高级别的 View 中,您可以将您的应用程序视为一个组件树,它的根是 AppComponent,因此 AppComponent 的子级必须放在 app.component.html 中,例如 NavBarComponent 的子级必须放在 navbar.component.html 内.

关于angular - 为什么没有 <app-root> 的其他组件不会出现在 index.html 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57916774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com