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

Error Alert: missing property data in angular 5 type

I attempted to design an interface in interface.ts. The data consists of an array of objects inside the Column. Below is the code for my interface: export class User { result: boolean; messages: string; Column=[]; data=[]; } export class Column { name ...

Elements constrained by themselves in a rest parameter with generic types

When using Typescript, it is possible to infer tuple types for generic rest parameters that are constrained by an array type. However, in my specific case, this functionality does not seem to work as expected. I am attempting to pass a series of pairs co ...

Creating dynamic components in Angular 2 and adding them to the view container of the body

I've been grappling with the challenge of dynamically generating a component and then adding it to the document tag. My struggle lies in figuring out the proper method for selecting the body's ViewContainerRef so that I can easily append a new co ...

Looking for a solution to the error message: "X is not able to be assigned to the type 'IntrinsicAttributes & Props'"

Greetings everyone! I need some assistance in setting up single sign-on authentication using React, Azure AD, and TypeScript. I'm encountering a type error in my render file and I'm unsure of how to resolve it. Below is the specific error message ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

Experiencing difficulties with a click event function for displaying or hiding content

Struggling with implementing an onClick function for my two dynamically created components. Currently, when I click on any index in the first component, all content is displayed. What I want is to show only the corresponding index in the second component ...

How can I detect when the Redux state object in my Angular (v5) application changes?

Can someone please explain to me the process of creating a listener, like subscribing to the AppState changing? Here is the basic service I currently have. In my view, there is a dispatch action that increments the counter. After the counter changes valu ...

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 ...

Updating the date format of [(ngModel)] with the ngx-datepicker library

One of the challenges I'm facing is dealing with a web form that captures date of birth. To accomplish this, I'm utilizing the ngx-bootstrap version 2.0.2 datepicker module. The issue I encounter lies in the fact that my API only accepts date val ...

Encountering an issue on Safari: WeakMap variable not found in .NET Core 1.1.0 and Angular 2 application

I recently deployed a .NET Core 1.1.0 + Angular 2 + Typescript app on ASPHostPortal and encountered an issue while accessing it from Safari. The console showed the following exception: Can't find variable:WeakMap This caused the site to not load p ...

Guide on integrating a newly bought template into an Angular 6 and Bootstrap 4 application

Although I have years of experience as a backend developer, I am relatively new to frontend development. Lately, I have been immersing myself in learning Angular 6 and Bootstrap 4 for an upcoming project at work. After setting up a basic Angular 6 applica ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

Secure method of utilizing key remapped combined type of functions

Imagine having a union type called Action, which is discriminated on a single field @type, defined as follows: interface Sum { '@type': 'sum' a: number b: number } interface Square { '@type': 'square&apos ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...

Jest Test - Uncaught TypeError: Unable to create range using document.createRange

my unique test import VueI18n from 'vue-i18n' import Vuex from "vuex" import iView from 'view-design' import {mount,createLocalVue} from '@vue/test-utils' // @ts-ignore import FormAccountName from '@/views/forms/FormAcco ...

Issue with Type-Error when accessing theme using StyledComponents and TypeScript in Material-UI(React)

I attempted to access the theme within one of my styled components like this: const ToolbarPlaceholder = styled('div')((theme: any) => ({ minHeight: theme.mixins.toolbar.minHeight, })); This information was found in the documentation: htt ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Obtain JSON information in a structured model layout using Angular 4

I have different categories in the backend and I would like to retrieve them in a model format. Here is how my model is structured: export class Category { name: string; id : string; } And this is how the data appears in the backend: { "name": "cars", ...

The error message "Module 'electron' not found" is commonly encountered when working with Electron and TypeScript

Hey there! I'm having some trouble with Electron not supporting TypeScript on my setup. I'm using vscode 1.16.1 and here is an overview of my package.json: { [...] "devDependencies": { "electron": "^1.6.13", "ts-loader": "~2.3.7", ...

Tips for creating a table in Angular 2

I need help creating a new row in a table using Angular. I know how to do it in pure Javascript, like the code below where addRow() method is called to generate a new row. But I'm new to Angular and want to learn the correct way to achieve this withou ...