javascriptangulartypescriptangular-materialstackblitz

Making the Angular Material Select Demo Stackblitz into a Standalone Component?


Trying to make the Angular Material Select Demo into a standalone component.

This is the Stackblitz.

These are the steps.

Replace main.ts with this (For booting standalone component):

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Routes } from '@angular/router';
import { SelectFormExample } from './app/select-form-example';

const routes: Routes = [];

bootstrapApplication(SelectFormExample, {
  providers: [provideRouter(routes)],
});

And make the component standalone like this ( Add standalone and imports. The imports come from app.module.ts):

/**
 * @title Select in a form
 */
@Component({
  standalone: true,
  imports: [
    FormsModule,
    HttpClientModule,
    MatNativeDateModule,
    ReactiveFormsModule,
    MaterialExampleModule,
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
  ],
  selector: 'select-form-example',
  templateUrl: 'select-form-example.html',
})

At this stage it compiles fine, but throws the error:

ROR Error: Providers from the `BrowserModule` have already been loaded. If you need access to common directives such as NgIf and NgFor, import the `CommonModule` instead.

The CommonModule is already included, and if BrowserModule is removed, it creates other problems.

Any ideas on how to fix this?


Solution

  • When application bootstrapped using the bootstrapApplication function we need to provide animation module in main.ts

    main.ts

    bootstrapApplication(SelectFormExample, {
      providers: [
        provideAnimations(),
        provideHttpClient()
      ],
    });
    

    Reference

    Working Example