Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following:

    export var initialComponents = [];
    initialComponents.push(AppComponent);
    if(condition) {
      initialComponents.push(IchFooterComponent);
    }

and then

bootstrap: initialComponents

This resulted in the following error message:

Error: The module oa was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.

Answer №1

To personalize the bootstrapping process, you can implement the ngDoBootstrap method within the AppModule. Include the components that need to be bootstrapped in the entryComponents property of @NgModule.

@NgModule({
    entryComponents: [AComponent, BComponent, ...]
    ...
 })
 export class AppModule {

     constructor() {}

 ngDoBootstrap(appRef: ApplicationRef) {
     if (Math.random() > 0.5) {
         appRef.bootstrap(AComponent, '#app');
     } else {
         appRef.bootstrap(BComponent, '#app');
     }
 }

If you require a service, you can access it via dependency injection by including it as a constructor parameter in the AppModule. However, any limitations compared to DI in components or services are unknown. Refer to the documentation for ApplicationRef and its bootstrap method.

Answer №2

Give it another shot (find the sample code below):

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; // <-- NgModel is here

import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';

var differentComponents: any[] = []; 

differentComponents.push(AppComponent);
if (true) {
  differentComponents.push(HeroesComponent);
}

@NgModule({
  declarations: differentComponents,
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class CustomModule { }

Give this a try:

https://stackblitz.com/edit/angular-vimqb1?file=src/app/app.module.ts

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

Handlers for event(s) not triggering on video element

In my NextJS application, I have implemented a feature to display a video file using the video element. I have added multiple event handlers to the video element: <video className='video-player' controls={true} preload='metadata&apo ...

object passed as value to competent parent

I'm facing an issue where I am trying to pass a value to the parent component, but it is returning an object instead of the expected value. Here's what I have: Child Component render() { return ( this.props.data.map((val, idx) => { ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

What is the reason behind the inability of the Angular/TypeScript HTTP GET method to accept a JSON object as a parameter

EXAMPLE 1 passJSONObj(){ let name = 'user names', let email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a2a4b2a5b2bab6bebb97b3b8bab6beb9f9b2afa3">[email protected]</a>&ap ...

Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner: Child Component: props: { idInput: { type: String, required: false }, nameInput: { type: String, required: false }, }, data() { return { id: this.idInput, na ...

What steps can be taken to verify if the user has transmitted a JSON Web Token?

Recently started using Express and been struggling with this particular error for quite a while. const token=req.header("jwt") console.log(token) if(!token ){ return res.json('no jwt') console.log('nojw ...

JavaScript's getElementsByName() method allows for easy access and

Excuse my lack of experience... I am attempting to run a javascript using the getElementByName method, with the goal of entering 0 in the quantity field on a particular site after 15 seconds of arriving there. Upon inspecting the quantity field, here is w ...

I am struggling to understand why clicking this button is not successfully submitting the form to Google Sheets

I am facing an issue with my Google Sheet setup that collects form data from my website. The problem is, I am unable to link the event to a button that already exists ('CompleteOrder'). Strangely, it works perfectly fine if I add a new button: & ...

Is there a way to streamline a function that substitutes certain words?

Looking for ways to simplify my function that shortens words when the label wraps due to different screen resolutions. It seems like it could be more efficient to use arrays for long and short word pairs, but I'm not sure how to implement it. Check ou ...

Ways to engage with a fixed html page generated by an Express router?

Let me start by mentioning that I am relatively new to working with NodeJs. Currently, I am dealing with a situation where I need to render a static HTML web page (which includes JavaScript code) as a response to a post request. Below is the relevant snipp ...

Double invocation of ActivatedRoute.params.subscribe method observed

To extract URL parameters, I'm utilizing the ngOnInit() method where I've implemented the following snippet: this.activatedRoute.queryParams.subscribe(params => { console.log(params); // actual implementation here }); Yet, upon initi ...

What is the best way to superimpose an image onto a canvas?

I am working on a cool project where I have created a canvas that displays matrix binary code raining down. However, I would like to enhance it by adding an image overlay on top of the canvas. Here is my current setup: <div class="rain"> ...

How to overcome the issue of Vue.js mobile router-link being blocked by v-on:mouseover

Here is a for list snippet: <li class="projects-item" v-for="project in filteredProjects" :key="project.id" v-on:mouseover="displayHoverInfo($event, project)" v-on:mouseleave="hover = false" > <router-link v-bind:to="'/project/ ...

Issue with handsontable numbro library occurs exclusively in the production build

Encountering an error while attempting to add a row to my handsontable instance: core.js.pre-build-optimizer.js:15724 ERROR RangeError: toFixed() digits argument must be between 0 and 100 at Number.toFixed () at h (numbro.min.js.pre-build-op ...

How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content o ...

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...

Adjusted position of the viewport if the DOM element containing the renderer is not located at the top of the display

I've come across an issue with a three.js scene within an Angular custom directive in the view. At the top, there's a navigation bar for switching between views (pretty standard so far). I set up a simple scene with a cube and basic camera rotati ...

Having trouble with Redux asynchronous operation while trying to access the current state?

Having some asynchronous issues with getting the state in my component. It's working fine when I console log in mapStateToProps, but for some reason it shows the old state when I console log inside render function. Any ideas on how to properly chain f ...