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]. https://i.sstatic.net/g8z6Q.png

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

Encountered numerous issues while attempting to execute the npm install -g angular-cli command

I encountered several errors while attempting to run the command npm install -g angular-cli on my Windows 10 64-bit system. Here's a look at the log: npm ERR! git clone --template=C:\Users\ben\AppData\Roaming\npm-cache\_ ...

Ways to update a value in a table by comparing two JSON objects

I am currently working with two JSON files containing data as shown below: JSON 1: let classes = [{ "Class": "A", "as_of": "12/31/2020", "student": [{ "raji": { "eng": ...

Implementing a JQuery click method within a class structure

I'm having trouble getting the functionality of the .click function to work on my page unless I paste it into the browser console. In my class, this is what I have: var myClass = function(){ var toggleChecked = function(){ $('#myCheck ...

Fetching the "User ID" variable from localStorage to PHP with angularjs - a quick guide

My goal is to retrieve "Notes" based on the "userID" value. Here is my approach: I used angular.js to trigger the PHP function $scope.getData = function(){ $http.get( '../php/displayNotes.php' ).success(function(data){ $ ...

"assurance of not issuing a return value in the correct order

Hey everyone, I'm a newcomer to the world of Ionic! I'm looking to pull data from pouch-db in the background. After some research, it seems like promises are the way to go. My goal is to have my console logs display in the order: 1, 2, and then ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

Ways to turn off Typescript alerts for return statements

I'm looking to turn off this Typescript warning, as I'm developing scripts that might include return values outside of a function body: https://i.stack.imgur.com/beEyl.png For a better example, check out my github gist The compiled script will ...

Is there a way to manipulate the appearance of a scroller using JavaScript?

I'm intrigued by how fellow front-end developers are able to customize the scrollbar shape on a webpage to enhance its appearance. Can anyone guide me on using JavaScript to accomplish this? ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

Django plugin designed for showing a real-time feed of messages - powered by Dajax or Jquery?

Currently, I am attempting to set up a section in my Django application where updates or messages from the server can be displayed once specific tasks are done. I had initially looked into using a plugin that utilizes Dajax / Jquery for this feature, but ...

Submitting forms with Ajax in IE(8)

Sample Google form Related spreadsheet I modified the original code to create two custom forms: First created form Second created form Both forms are functional on most browsers except for IE(8). Any idea why? First form: <!DOCTYPE html> <h ...

How do I specify TypeScript types for function parameters?

I've created a function and used TypeScript to define parameter types: const handleLogin = async ( e: React.FormEvent<EventTarget>, navigate: NavigateFunction, link: string, data: LoginDataType, setError: React.Dispatch<Re ...

The abundance of information presented in the "object" type, specifically "[object Object]," prevents serialization as JSON. It is advised to exclusively provide data types that are JSON

Utilizing NextJS, I initially made internal calls to a /api route using fetch(). However, for production, it was evident that internal api calls within getServerSideProps are not allowed. Consequently, I am attempting to directly access my MongoDB database ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

Authenticate with Google using the Javascript API without causing a pop-up to appear

Here is the code I'm using to allow users to log in with their Google account via the Javascript API. HTML <a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a> Javascript function gPOnLoad ...

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

What sets $emit and $dispatch apart in Vue.js?

Vue 2.0 has deprecated the use of $dispatch and $broadcast. I have noticed that $dispatch is similar to $emit. What are the key differences between them? Can we safely replace $dispatch with $emit during migration? ...

Adjust variable values when the window is resized

I've been working on getting some variable values to update when the window is resized. After researching, I learned that it's recommended to declare the variables outside of the .resize function scope and then try to change their values within ...

Learn the process of importing data types from the Firebase Admin Node.js SDK

I am currently facing a challenge with importing the DecodedIDToken type from the https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.decodedidtoken. I need this type to be able to assign it to the value in the .then() callback when v ...

Alternating the main access point from a separate module

I'm finding it difficult to understand why this should be so simple, but I just can't seem to solve this issue. Within my application, I have various root routes like login, events, and more. To manage the main menu functionality, I created a mo ...