Search code examples
angularweb-componentangular-standalone-components

Can I set CUSTOM_ELEMENTS_SCHEMA globally in Angular 17 without an application module?


I have recently migrated my project to Angular 17 and as part of that upgrade I removed app.module.ts, migrating its configuration to app.config.ts. I also migrated from Material Angular to using some web components.

Currently, I am forced to introduce in every component schemas: schemas: [CUSTOM_ELEMENTS_SCHEMA]. Since I will use these web components in every component I want to include this property globally so that I don't have to write it for every component. If I was using app.module.ts I know that this would have been possible, however in my current configuration I am not sure how to do that.

For reference, here are my two entry files:

main.ts:

import {appConfig} from './app/app.config';
import {bootstrapApplication} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';

bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));

app.config.ts:

import {ApplicationConfig, importProvidersFrom} from '@angular/core';
import {provideRouter} from '@angular/router';

import {routes} from './app.routes';
import {provideHttpClient, withInterceptors} from '@angular/common/http';
import {CookieModule} from 'ngx-cookie';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(),
    importProvidersFrom(CookieModule.withOptions()),
  ],
};

I am looking for a solution that will not make me create an app.module.ts

I tried to see if I could include the "schemas" property in my appConfig object, however that did not work. I also tried searching online for this specific issue but I only found the solution for including it in app.module.ts


Solution

  • When you use this CUSTOM_ELEMENTS_SCHEMA you are making your application ignore many crucial errors which help you during development, instead just register the web components.

    import { createCustomElement } from '@angular/elements';
    import { createApplication } from '@angular/platform-browser';
    import { ToggleComponent } from './app/toggle/toggle.component';
    
    (async () => {
    
      const app = await createApplication({
        providers: [
          /* your global providers here */
        ],
      });
    
      const toogleElement = createCustomElement(ToggleComponent, {
        injector: app.injector,
      });
    
      customElements.define('my-toggle', toogleElement);
    
    })();
    

    Angular Elements: Web Components with Standalone Components

    How to build web components from Angular elements