Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules

In my index.html, I have included the code snippet below:

  <app-header>Loading header...</app-header>
  <app-root>Loading...</app-root>
  <app-footer>Loading footer...</app-footer>

The components mentioned in the code above are being supplied in my app.module.ts for bootstrapping:

bootstrap: [AppComponent,HeaderComponent,FooterComponent]

These components are then bootstrapped in my main.ts file as follows:

platformBrowserDynamic().bootstrapModule(AppModule);

Currently, the application functions correctly when all three modules are included. However, if any one of them is removed, the app continues to work but errors are displayed in the console[img attached].

I am attempting to create standalone modules within a single component that can be easily integrated or excluded from the application as needed. For example, having separate modules for the header, footer, and body allows flexibility in selecting which components to include based on specific page requirements. In certain instances, excluding the app-header may be necessary.

Would appreciate feedback on whether my approach aligns with best practices?

Answer №1

I stumbled upon this article and it worked perfectly for me

import { NgModule, Injectable, APP_INITIALIZER, ApplicationRef, Type, ComponentFactoryResolver } from '@angular/core';
import {FooterComponent} from './footercomponent';
import {AppComponent} from './appcomponent';
import {HeaderComponent} from './headercomponent';

const components = [AppComponent, HeaderComponent, FooterComponent];

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  entryComponents: components,
  providers: []
})
export class AppModule {

    constructor(private resolver: ComponentFactoryResolver) { }

    ngDoBootstrap(appRef: ApplicationRef) {
        components.forEach((componentDef: Type<{}>) => {
            const factory = this.resolver.resolveComponentFactory(componentDef);
            if (document.querySelector(factory.selector)) {
                appRef.bootstrap(factory);
            }
        });
    }
}

Answer №2

Utilizing Modules:

@NgModule({
  declarations: [App1],
  exports: [App1]
})
export class App1Module
  
@NgModule({
  declarations: [App2],
  exports: [App2]
})
export class App2Module
  
@NgModule({
 imports: [App1Module, App2Module],
 exports: [App1Module, App2Module]
})
export class MainModule

When incorporating these modules, you can choose to include all of them or only the ones that are relevant.

While you have the option to create separate modules for each component and import them as needed, you can also bootstrap multiple components by listing them in an array under the 'bootstrap' property.

For example:

@NgModule({
  imports: [],
  declarations: [App1, App2, App3],
  bootstrap: [App1, App2, App3]
})
export class BaseModule {}

If all the bootstrapping components are set up correctly from the beginning, something like this should work:

<body>
   <app1>App1</app1>
  <app2>App1</app2>
  <app3>App1</app3>
</body>

This approach is worth trying out for your project requirements.

For more detailed information:

How to dynamically create bootstrap modals as Angular2 components?

https://plnkr.co/edit/akm7OPahe72Ex9i2ZXej?p=preview

I hope this explanation proves useful. Feel free to reach out for further assistance.

Let me know if you require any additional modifications.

Answer №3

Hey there,

If I were in your shoes, I'd start by bootstrapping the whole application in one go:

<fullApp>Loading...</fullApp>

Afterwards, I'd create separate components for the header and footer and then include them as nested views within the main component.

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

Having difficulty automatically populating a textarea with the chosen option from a datalist

Is there a way to automatically populate the Address field of a client in a textarea based on the input of the client's name in an input field? I have created a 'for loop' to retrieve a datalist of client names. For the address, I retrieved ...

Accessing an array outside of an Ajax call that was initiated within a success callback

I have a CSV parsing function written in JavaScript that extracts movie names from a CSV file using an Ajax call within a loop. movies = new Array(); for (var i = 1; i < allData.length; i++) { var mName = allData[i][0]; var mPath = allData[i ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

How to completely disable a DIV using Javascript/JQuery

Displayed below is a DIV containing various controls: <div id="buttonrow" class="buttonrow"> <div class="Add" title="Add"> <div class="AddButton"> <input id="images" name="images" title="Add Photos" ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information. <script> document.addEventListener('DOMContentLoaded', ...

Unable to establish proper functionality of username variables in Node.js chat application

For my latest project, I am developing a chat application in node.js following a tutorial from socket.io. The main objective of the app is to allow users to input their username along with a message, which will then be displayed as "username: message" in t ...

Is there a way to sort through a JSON object using JavaScript?

I have a JSON string that looks like this: { "Animal":{ "Cat":20, "Dog":10, "Fish":5 }, "Food":{ "Pizza":500, "Burger":200, "Salad" ...

Angular NgFor directive for rendering data

Is it possible to showcase information from a selected *ngFor on another page? For instance, I have two pages: result.component.html and details.component.html result.component displays data using *ngFor while details.component showcases the details of th ...

Arrange the angular datatables in a specific order without displaying the usual user interaction triangles

I am looking to arrange the data in a fixed manner without any user interaction for sorting. However, it seems that I can either completely disable ordering like this: this.dtOptions = { paging: false, lengthChange: false, searching: false, orderi ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

Issue encountered during the process of importing Excel information utilizing the xlsx library

Currently, I am attempting to incorporate excel data into my angular application using the following library: xlsx However, upon downloading the project and attempting to run it locally, I encountered an error when trying to upload the excel file: Uncau ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

What is the reason for the malfunction in the login dialog?

I'm having trouble implementing AJAX login functionality on my website. When I click the submit button, nothing seems to happen. Can someone take a look at the code and help me out? $(document).ready(function() { var user, pass; function login(us ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

Error: The window object is not found in this context when initializing the Commerce module from the commerce.export.js file located in the node_modules folder within the @chec

I have been working with the pages router and custom app file (_app.js) https://nextjs.org/docs/pages/building-your-application/routing/custom-app It seems that the issue may be within my _app.js file, where I have the following code: import '../glo ...