Angular - 在index.html中显示组件

问题描述 投票:0回答:1

我正在尝试显示 index.html 中的

create-form-component

我有:

import 'zone.js/dist/zone';
import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { BirdCreateFormComponent } from './create-form/create-form.component';

@NgModule({
  declarations: [BirdCreateFormComponent],
  imports: [CommonModule],
  bootstrap: [App],
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

在index.html中:

<body>
  <my-app>Loading...</my-app>
  <create-form></create-form>
</body>

但是

<create-form>
标签被忽略 - 为什么?

Stackblitz 这里

我是 Angular 的新手,所以围绕答案进行叙述会很棒。

html angular angular-components
1个回答
1
投票
  1. App
    是 Angular 应用程序的起始(根)组件。因此你无法在index.html中渲染
    BirdCreateFormComponent
    ,但你需要通过
    App
    来渲染
    BirdCreateFormComponent

  2. 您混淆了

    NgModule
    Component
    App
    。从 Angular 15.2 开始,它支持在没有根模块的情况下引导独立组件。

如果您正在寻找引导独立组件解决方案,您需要将组件构建为

standalone

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, BirdCreateFormComponent],
  template: `
    <create-form></create-form>
  `,
})
export class App {
  ...
}
@Component({
  selector: 'create-form',
  templateUrl: './create-form.component.html',
  standalone: true,
  styleUrls: ['./create-form.component.css']
})
export class BirdCreateFormComponent {
   ...
}

参考:将现有的 Angular 项目迁移到独立项目

演示引导独立组件@StackBlitz


或者,如果您正在寻找引导模块,则需要根模块并引导它。

import {
  BrowserModule,
  platformBrowser,
} from '@angular/platform-browser';
import { BirdCreateFormComponent } from './create-form/create-form.component';

@NgModule({
  declarations: [App, BirdCreateFormComponent],
  imports: [BrowserModule],
  bootstrap: [App],
})
export class AppModule {}

platformBrowser()
  .bootstrapModule(AppModule)
  .catch((e) => console.error(e));
@Component({
  selector: 'my-app',
  template: `
    <create-form></create-form>
  `,
})
export class App {
  ...
}

演示引导模块@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.