Is there a way to incorporate a personalized angular element into a component's html file without using index.html?

Angular version in use: v11

I am currently attempting to incorporate an application with lazily loaded modules as angular elements using ngx-build-plus into another application. I am encountering challenges when trying to add the element to a component within the primary application. While it successfully renders when added to the index.html, I encounter an error when attempting to include it in any other HTML file.

'cs-root' is not recognized as an element:
1. Verify if 'cs-root' is an Angular component and ensure that it belongs to this module.
2. If 'cs-root' is a Web Component, include 'CUSTOM_ELEMENTS_SCHEMA' in the '@NgModule.schemas' of this component to suppress this message.

The configuration of the app module file can be seen below:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    RouterModule,
    AppRoutingModule,
    CoreModule.forRoot(),
    SharedModule.forRoot(),
    ToasterModule
  ],
  exports: [AppComponent],
  providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpAuthInterceptor, multi: true },
    { provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [AppInitService], multi: true },
     WindowService,
     InsightsGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    const el = createCustomElement(AppComponent, { injector });
    customElements.define('cs-root', el);
  }
  ngDoBootstrap() {
    // This method bypasses the natural bootstrapping of the element 
    }
}

Is there something essential that I may have overlooked?

Answer №1

Successfully resolved the issue

Inserted the following code into the component (where I needed to include the Angular element).

if (!document.getElementById('cs-root')) {
   this.loadExternalService.addExternalScript(renderer2);
   const customElement = document.createElement('cs-root');
   const contentHolder = this.el.nativeElement;
   contentHolder.appendChild(customElement);
}

el: ElementRef

load-external-files service

const customPath = 'http://localhost:4600/'
public addExternalScript(renderer2: Renderer2): void {
   const script = renderer2.createElement('script');
   script.type = 'text/javascript';
   script.text = ``;
   script.src = `${customPath}[es2015-bundle-file-name].js`;
   script.onload = this.loadNextScript.bind(this, renderer2, cdnUrl);
   renderer2.appendChild(this._document.body, script);
}
private loadNextScript(renderer2: Renderer2) {
  const script = renderer2.createElement('script');
  script.type = 'text/javascript';
  script.text = ``;
  script.src = `${customPath}[es5-bundle-file-name].js`;
  script.onload = () => {
       // logic on files load
  };
  renderer2.appendChild(this._document.body, script);
}

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

What is the best way to access values from dynamically added components in Svelte when using data from a REST API in a loop?

Previously, I posted this query but now I've made changes to utilize a REST service for retrieving the item list. Everything functions as expected when the data is hardcoded, however, I encounter undefined values when using data from the REST service. ...

The Name 'require' could not be found (TS2304)

My app is encountering a build error with Webpack, specifically due to awesome-typescript-loader. The error message reads as follows: ERROR in [at-loader] ./src/app/app.ts:6:13 TS2304: Cannot find name 'require'. Here is the code snippet cau ...

Ways to indicate certain columns as highlighted and others as not chosen in the PrimeNg Multiselect module

Looking to customize the display of columns in Primeng Multiselect: how can I show only selected columns that have their 'display' property set to true? this.columns = [ { field: 'A', label: 'A', display: true }, { field: &ap ...

Utilizing Ionic's @capacitor/google-maps to find directions on Google Maps between two different routes

I am currently developing a taxi application that requires displaying the direction between two locations. When a customer clicks on navigate, I aim to implement live tracking similar to Google Maps. Here is what I have accomplished thus far: // Obtainin ...

What are the best practices for implementing Alertify in a Typescript project?

I'm relatively new to Angular2 so please bear with me. I attempted to implement Alertify.js in my Angular2 project for a custom dialog box, but I am encountering difficulties getting Alertify to work properly. Since I lack deep knowledge of JavaScrip ...

Deactivating upcoming weeks according to the year in Angular 8

In the user interface, there are dropdowns for selecting a year and a week. Once a year is selected, the list of weeks for that year is displayed in the week dropdown. Now, the requirement is to disable the selection of future weeks. For example, for the ...

How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature. Now I am attempting to have the data app ...

Utilizing Props in Next.js with a Form Component

Currently, I am diving into the world of Nextjs and facing a challenge in passing a variable through a form component, and then further through its server action component. (I believe this is referred to as prop drilling, and I'm exploring if there&ap ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

Ways to Prompt a User to Select the "Remember Me" Option

How can I implement the functionality of 'Remember Me' on a login page? I want users who click on 'Remember Me' to be able to reopen the page without logging in again, even after closing their browser. But how do I differentiate between ...

Understanding TypeScript's noUnusedParameters compiler option clarifications

I'm currently investigating whether this issue qualifies as a bug prior to submitting it on GitHub. When the noUnusedParameters setting is activated, the TypeScript compiler will generate an error in scenarios like this: const foo = ['one' ...

Unable to circumvent the Angular sanitize security measures

Using a wysiwyg editor (angular-editor): <angular-editor [(ngModel)]="code" name="code"></angular-editor> Underneath the editor, attempting to implement ngx-highlightjs: <pre> <code [highlight]="code" [lineNumbers]="true"></ ...

Is it possible to determine when a component has completed its rendering process in Angular?

I am currently working on an Angular application where I have a page component that contains several subcomponents. Each subcomponent is set up to fetch data from an API in the ngOnInit method, causing a layout shift issue as they load at different speeds ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

What is the proper method for utilizing TypeScript declarations (*.d.ts) and interfaces?

When working with interfaces in TypeScript, there are two main approaches to consider. The first involves defining them in regular .ts files and importing them as needed. The second option is to define the interfaces in .d.ts files and let the compiler dis ...

Skipping emission during the parsing of TypeScript configuration files

Encountering an issue with the node-config library while using typescript. The structure of my config folder is depicted here: https://i.sstatic.net/BKBgv.png After running tsc and attempting to launch my app from its entry point (app.js), a error ...

What is the procedure for adding a background to a primeNg Tree component?

Working with Angular CLI 6 and primeNg version 6.0.1 I have been attempting to customize the background of the tree component without success. When I try using style="background:red" in the HTML file, the tree display becomes distorted with a height of on ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

Verify the attribute of the child element

In my child component, I have a property named files, which is an input type=file. This property allows me to determine if the user has selected a file for upload so that I can disable the submit button if no files are present in the input field. The issue ...