Angular threw an error saying: "Template parse errors: is not a recognized element"

I am attempting to utilize babel standalone within a react application to transpile Angular TypeScript. The transpiling process seems to be successful, however, I encounter an error when trying to import a component and use its selector within the template of another component.

The error message that is displayed:

Uncaught Error: Template parse errors:
'search-bar' is not a known element:
1. If 'search-bar' is an Angular component, then verify that it is part of this module.
2. If 'search-bar' is a Web Component, then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

SearchBar Component (user code):

// ng is located on the window object
const { Component, NgModule, Output, EventEmitter } = ng.core;
const { CommonModule } = ng.common;

@Component({
  selector: 'search-bar',
  template: `<div>Search Bar</div>`,
})
@NgModule({
  declarations: [SearchBar],
  exports: [SearchBar]
})
class SearchBar {}

export default SearchBar;

App Component (user code):

const { Component, NgModule, VERSION } = ng.core;
const { CommonModule } = ng.common;

// Note: The online editor does not require a path to the component :)
import SearchBar from 'SearchBar.ts';

@NgModule({
  imports: [
    CommonModule,
    SearchBar,
  ],
  declarations: [AppComponent, SearchBar],
})
@Component({
  selector: 'my-app',
  template: `<search-bar></search-bar>`
})
export default class AppComponent {

}

It is essential to mention that I am developing an online code editor which necessitates the usage of babel standalone. Below is my babel configuration for typescript:

(extracted from my react app)

const TS_OPTIONS = {
  presets: [
    ['typescript', { allExtensions: true }],
    ['es2017', { 'modules': false }],
  ],
  plugins: [
    ["proposal-decorators", { "legacy": true }],
    ["proposal-class-properties", { "loose" : true }],
    'transform-modules-commonjs',
  ],
};

Babel version being utilized:

https://unpkg.com/@babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="added9ccc3c9ccc1c2c3c8ed9a839c9f8394">[email protected]</a>/babel.min.js

My simplified transpile function (also extracted from my react app):

export default function transpile(myCode) {
  const { code } = Babel.transform(myCode, TS_OPTIONS);

  return myCode;
}

What could I possibly be overlooking?

Answer №1

At some point, I ended up making a mistake and CodeMonkey was quick to point out that I should not have NgModule in my components. I will give credit to him for the solution, but just to provide a complete example in case someone needs it. It's worth noting that there are some syntax rules specific to my online code editor (such as not needing a file path when importing components).

Main Component with Module:

// main.ts
// contains my module
const { Component, VERSION } = ng.core;
const { BrowserModule } = ng.platformBrowser;
const { NgModule } = ng.core;
const { CommonModule } = ng.common;

import AppComponent from 'App.ts';
import SearchBarComponent from 'SearchBar.ts';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
  ],
  declarations: [AppComponent, SearchBarComponent],
  bootstrap: [AppComponent],
  providers: []
})
class AppModule {}

const { platformBrowserDynamic } = ng.platformBrowserDynamic;

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

App Component:

// App.ts
const { Component } = ng.core;

@Component({
  selector: 'my-app',
  template: `
  <h1 [innerHTML]="title"></h1>
  <search-bar></search-bar>`
})
export default class AppComponent {
  title;

  constructor() {}

  ngOnInit() {
    this.title= "Hello World!";
  }
}

SearchBar Component:

// SearchBar.ts
const { Component } = ng.core;

@Component({
  selector: 'search-bar',
  template: `<h1>Search Bar</h1>`
})
export default class SearchBarComponent {}

Answer №2

Upon reviewing this code snippet, I couldn't help but notice the combination of a class serving as both a module and a component. In my experience, it's more common to have separate classes for these two functionalities.

// The 'ng' object is accessible from the window
const { Component, NgModule, Output, EventEmitter } = ng.core;

@Component({
  selector: 'search-bar',
  template: `<div>Search Bar</div>`,
})
export class SearchBar {}

@NgModule({
  declarations: [SearchBar],
  exports: [SearchBar]
})
export class SearchModule {}

I'm curious if you've encountered any instances of dual purpose classes being used effectively elsewhere?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the ternary operator in Angular HTML templates

Using the ternary operator in HTML can simplify your code: <div> {{ showStringOneFlag ? 'Display String 1' : 'Display String 2' }} </div> This approach could save you from setting a string variable multiple times in JavaSc ...

Dynamically adjust the label position based on the button position

I am currently developing an interface that allows users to change the position of buttons and add a label text under the button. However, I am facing an issue where the label is not always centered below the button due to variations in the size and number ...

What is the proper way to import and define typings for node libraries in TypeScript?

I am currently developing a node package in TypeScript that utilizes standard node libraries such as fs, path, stream, and http. Whenever I attempt to import these libraries in a .ts file, VS Code flags the line with an error message: [ts] Cannot find m ...

When the observable is subscribed to, the data is not immediately available

I am encountering an issue with syncing data from an observable in a service with a component that consumes the data. The data service makes a call to an api service upon creation to gather a list of devices from a server. It seems like this process is fun ...

Sending information from one Angular 2 component to another

As a newcomer to Angular 2, I am still in the process of understanding its functionalities. Currently, I have two components: 1) List Component This component is responsible for displaying all the products in a store and performing various functions. @C ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Updating Key-Value pairs in an ArrayList using Angular 4

After importing json data into an arrayList and storing it in local-storage, the structure looks like this: [ { "id": 1, "name": "Albany", "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g", "price": 1 ...

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

Encountering a 403 error upon refreshing the page of my Angular 6 project

I am currently working on an Angular 6 project with JWT authorization deployed on AWS Elastic Beanstalk and utilizing CloudFront. I am using the @auth0/angular-jwt library to manage everything efficiently. The setup is functioning smoothly, and I have a li ...

Steer clear of using the non-null assertion operator while assigning object members

Looking for a practical method to assign object members to another object without using the non-null assertion operator "!". In the example below, consider that formData can be any JavaScript object. some.component.ts export class SomeComponent { someMo ...

Dealing with nullable properties in Typescript

In my React Component code snippet, I am facing an issue with an optional field that needs to be initialized as undefined. This is causing difficulties when trying to use it after type checking. The problem arises in the context of using typescript version ...

Is there a method to prevent explicitly passing the context of "this"?

Currently, I am in the process of developing a new product and have set up both back-end and front-end projects. For the front-end, I opted to use Angular framework with Typescript. As a newcomer to this language (just a few days old), I have encountered a ...

Mastering the TestBed in Angular for precise implementation

In my Angular 8.1.2 and Ionic 4 app project, I decided to write unit tests for a simple TypeScript class. Initially, running the tests with "npm test" worked perfectly. However, as I prepared to tackle more complex classes requiring mocking, I refactored t ...

Having trouble with browser freezing when using array push in Angular 4? Looking for a solution to fix this issue?

In my logsCompoment.ts file, there is an array called logs where I store new log entries and display them on the HTML page using ngFor directive. I achieve this by handling incoming data in the following manner: this.socket.on('newline', (data) ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

The object literal's property 'children' is assumed to have a type of 'any[]' by default

Is there a way to assign the property myOtherKey with any value? I encountered a Typescript error that says.. A problem occurred while initializing an object. The property 'children' in the object literal implicitly has an array type of 'a ...

Troubleshooting a problem with Angular2 involving the This.http.get function

Currently, I am delving into Angular 2 and have set up an ASP.NET WebApi locally hosted in IIS at http://localhost:8081/ping. The API call successfully returns a string serialized as a JSON Object. Below is the code for my service: import { Injectable } ...

Angular mobile navbar experiencing collapse issue

I am working on an Angular project that does not include Jquery. I am trying to implement a navbar using mdbootstrap, but I am encountering issues with the collapse feature not working properly. Below is the HTML content I am using: <header> < ...

The mat-table fails to populate with data retrieved from the rest service

I have successfully fetched an array from my REST service and displayed some information from the response on the page. However, I am facing issues populating my mat-table and I'm unsure of the cause. The mat-table was functioning properly in the past ...