Is there a way of providing the common module in all modules in Angular StandAlone?

218 views Asked by At

In every component I have to import this CommonModule to use directives like NgIf and so on.

I want a way of injecting this module in all my modules.

   @Component({
      selector: 'app-register',
      standalone: true,
      imports: [ReactiveFormsModule, CommonModule, TextInputComponent],
      templateUrl: './register.component.html',
      styleUrl: './register.component.scss'
    })
2

There are 2 answers

0
LogicBlower On

you need to specify modules in imports, that can't be avoided to resolve services and other dependencies.

you can use this common approach

create a shared module file and Add -"imports and exports" common module / some forms module in that (the one's that is being used in all / most of them ) , and then import that sharedModule in your component file. it will reduce no. of imports line in you standalone component.

0
kahve6 On

I recommend you to use @if to avoid duplicate modules. Further theoretical information is below if you wonder.

That's pretty much the point of a standalone component. It's completely standalone.

In your case what you can do is instead of a giant shared module that imports/exports shared code, make each component it's own module and export the component from the module. Then you can import each module individually within your app from shared/componentA, shared/componentB, etc. This way everything is in a module that can be shared without duplicating code.

From a discussion about Standalone Components and Modules. In addition to this quote, about working standalone with using shared modules or not, there is a big difference. Those are bundled separated and they allow for deep imports, meaning if I import a single component only that component is added, while a shared module bring all the components that are declared in it. And it means that you will import your standalone component to your root and it imports shared modules again. That's why duplicating codes bring loads to your application.

Example according to quote, FirstComponent.module.ts:

@NgModule({
  declarations: [FirstComponent],
  exports: [FirstComponent]
})
export class FirstComponentModule {}

app.module.ts:

@NgModule({
  declarations: [ ... ,
  ],
  imports: [...,
    FirstComponentModule
  ],
  exports: [ ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

This was the modular architecture.

If you want to pull your component out from your root and make it standalone, you shouldn't crack the architecture and that's why Angular made a new type of ngIf and ngFor like @if and @for.