0
0

#03 [Angular] Standalone components

Posted at

Introduction

Components declaration that we have learned is adding your components to the imports array in the @NgModule . It doesn't bother us when we just develop a TODO app or some small-scale project for study or mainly for fun. When having a large scale project, Angular's declaration can make the import list as long as you want. Or you don't? Maybe you can try the new staff from Angular 14, standalone components.

As the name they call "standalone", allow specifying components, directives or pipes independently without through the @NgModule and make life easier.

Create Standalone components

1. Add decorator to exist component

To create a standalone component, simply add standalone: true to @Component decorator or you can run the following command to create a new standalone component.

ng generate component [name] --standalone

2. Adopt standalone components to the existing application

It is very easy to apply standalone components to existing Angular applications. Using NgModule.imports and done.

@NgModule({
  //...
  imports: [StandaloneComponent]
  //...
})

3. Create a Standalone only application

Or you may want to use Standalone staff only in the new Angular application, Angular team provide bootstrapApplication API to meet your needs. You can pass providers to bootstrapApplication just like NgModule-based .

import {bootstrapApplication} from '@angular/platform-browser';
//...

bootstrapApplication(StandaloneComponent, {
  providers: [
    provideRouter([/* route */]),
    importProvidersFrom(TPLibrary.forRoot()),
    //...
  ]
});

Angular and third-party libraries have been updated to provide provide functions such as provideRouter for dependency injection configuration without NgModule. You can still use importProvidersFrom if a library only provides NgModule API.


Just a brief introduction to Angular standalone components and a memo for myself.

Resource

Angular Official Site: https://angular.io/guide/standalone-components

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0