0

Stackblitz has defaulted their Angular starters to opt-in to the new standalone Angular components. With this change, I'm encountering issues importing my custom component (FirstComponent) into their new "main" component declared in main.ts.

This is my simple custom component -

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-first',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css'],
})
export class FirstComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

I've added the standalone and imports properties in the selector, but that didn't help.

Here is their main.ts -

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  template: `
    <h1>Hello from {{name}}!</h1>
    <a target="_blank" href="https://angular.io/start">
      Learn more about Angular 
    </a>
    <app-first></app-first>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

This is the error -

Error in src/main.ts (15:5)
'app-first' is not a known element:
1. If 'app-first' is an Angular component, then verify that it is included in the '@Component.imports' of this component.
2. If 'app-first' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.

Here is the stackblitz URL - https://stackblitz.com/edit/stackblitz-starters-2hwyyr?file=src%2Fmain.ts

1 Answer 1

0

With standalone components, instead of importing NgModules into other NgModules, you are now able to import components directly into other components (providing both are standalone: true).

In this case you just need to make sure you import your FirstComponent class into the App component's imports list:

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [
    CommonModule,
    FirstComponent
  ],
  template: `
    <h1>Hello from {{name}}!</h1>
    <a target="_blank" href="https://angular.io/start">
      Learn more about Angular 
    </a>
    <app-first></app-first>
  `,
})
export class App {
  name = 'Angular';
}

https://stackblitz.com/edit/stackblitz-starters-gtdpfc?file=src%2Fmain.ts

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.