[Angular] The AppComponent class is a standalone component, which can not be used in the @NgModule.bootstrap array. Use the bootstrapApplication function for bootstrap instead

W starszych wersjach tworzony komponent musiał być zadeklarowany w NgModule, aby można było użyć go w szablonie innego komponentu. W klasycznym podejściu do organizacji komponentów w Angularze tworzymy tak jak pokazano poniżej:

import { Component } from '@angular/core';

@Component({

  selector: 'app-hello',
  template: `<h1>Hello, {{ name }}</h1>`,
  
})
export class HelloComponent {

  name: string = 'World';
  
}

Następnie w app.module.ts musimy zadeklarować komponent:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HelloComponent } from './hello.component';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloComponent, // Deklarujemy nasz komponent
  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [AppComponent] // Wskazujemy główny komponent do inicjalizacji
})
export class AppModule { }

Przy tworzeniu komponentów z nowym podejściem standalone component (komponent samodzielny) NgModule nie jest używane do deklarowania komponentu, więc aby użyć komponentu samodzielnego w innym należy go w nim zaimportować. Stwórzmy jeszcze raz HelloComponent, ale tym razem standalone:

import { Component } from '@angular/core';

@Component({

  standalone: true,
  selector: 'app-hello',
  template: `<h1>Hello, {{ name }}</h1>`,
  
})
export class HelloComponent {

  name: string = 'World';
  
}

Teraz możemy użyć tego komponentu, gdzie potrzeba bez deklarowania w NgModule, wystarczy tylko użyć tablicy imports. Załóżmy, że chcemy użyć 'HelloComponent' w głównym komponencie aplikacji:

import { Component } from '@angular/core';
import { HelloComponent } from './hello.component';

@Component({
  selector: 'app-root',
  template: `<app-hello></app-hello>`,
  standalone: true,
  imports: [HelloComponent],
})
export class AppComponent {}

Należy również dokonać zmian w pliku main.ts, jeśli korzystasz z Angular 14 lub starszych, ponieważ w nowszych wersjach inicjalizacja aplikacji jest inna niż w starszych. W nowych wersjach Angulara wygląda to podobnie jak poniżej:

import { enableProdMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Routes } from '@angular/router';
import { AppComponent } from './app/app.component';
import { environment } from './environments/environment';
import { AppRoutingModule } from './app/app-routing.module';

const routes = [];

if(environment.production) {

  enableProdMode();
  
}

bootstrapApplication(AppComponent, {

  providers: [
    provideRouter(routes)
  ]
  
}).catch(err => console.error(err));

Komentarze

Popular

[C++] Jak obliczyć pole i obwód trapezu?

[HTML] Jak wyśrodkować tekst?

[PHP|HTML] Odświeżenie strony