First, please note that using standalone components is not the new Angular 15 default. Generate a new app with ng new
and you'll find the expected module. The source of your troubles, is that StackBlitz decided to change their new app template in a way that harms the experience.
Using standalone components will actually complicate your life in a real application, but I digress.
You have two options to get your StackBlitz app working.
The first, as Harshit's answer shows partially, you can use standalone components throughout. It's the fewest changes you'll need, but quickly becomes onerous as your list of components grows. And if you're planning to copy the component to your app, you'll have to change it all back. Anyway, here's how:
Once you've generated a new component, add standalone: true
to its @Component
decorator.
@Component({
standalone: true, <-- This is new
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css'],
})
export class MyComponent implements OnInit {
Then, in every component that uses MyComponent
, add it to that component's import
clause:
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, MyComponent], <-- This is changed
template: `
<h1>Hello from {{name}}!</h1>
<my-component></my-component>
`,
})
export class App {
The alternative is to convert the new StackBlitz app to use a module. This is better, but more work.
- Generate a new module, named
AppModule
.
- Generate a new component, named AppComponent.
- Replace the contents of
main.ts
with the following:
import 'zone.js/dist/zone';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
At this point, StackBlitz goes nuts and tells you:
NG0400: A platform with a different configuration has been created.
To get rid of it, you need to save and reload the page.
- In
app.module.ts
, import your new component, bootstrap it, and import BrowserModule
. In short, your @NgModule
decorator should look like this:
@NgModule({
imports: [CommonModule, BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
- Finally, change your component's selector to match the default in
index.html
. Normally, that's <my-app></my-app>
, so you'll change your selector in app.component.ts
to my-app
:
@Component({
selector: 'my-app', <-- This is changed
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
Et voila! In five onerous steps, you can get StackBlitz back to a reasonable default. If you think that's daft, please let StackBlitz know on the GitHub issue.