Creating components with the viewContainerRef in Angular2 is functioning as expected

When attempting to load a dynamic component into the root component using viewContainerRef.createComponent, I encountered an issue where it appended to the wrong place.

https://i.stack.imgur.com/lF1yT.png

Here is my code:

-----app.compoment.ts-----

export class AppComponent { 
   private viewContainerRef:ViewContainerRef;
   public constructor(viewContainerRef:ViewContainerRef) {
    this.viewContainerRef = viewContainerRef;
  }
}

-----a.service.ts------

@Injectable()
export class ModalService {
  private viewContainerRef:ViewContainerRef;
    constructor(applicationRef: ApplicationRef, injector: Injector,private compiler: ComponentResolver) { 
        var classOfRootComponent = applicationRef.componentTypes[0];
        // this is an instance of application bootstrap component
        var appInstance = injector.get(classOfRootComponent);
        this.viewContainerRef= appInstance.viewContainerRef;
    }
    alert() {console.log(this.viewContainerRef);
        this.compiler.resolveComponent(ModalComponent)
        .then(
            (factory) =>
            this.viewContainerRef.createComponent(factory, 0, this.viewContainerRef.injector)
        ).then((componentRef) => {
                return componentRef;
            }
        );
    }
}

Answer №1

As per the design, this is intentional. For further information, refer to this conversation https://github.com/angular/angular/issues/9035

If you wish for <custom-modal> to be placed within <my-app>, include a target element in the template of <my-app> and designate it as the target.

You will need to transfer it from the AppComponent to the ModalService as shown below:

@Component({
  selector: 'my-app',
  template: `<div #target></div>`
})
export class AppComponent {
  @ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef;

  constructor(private modalService:ModalService) {}

  ngAfterViewInit() {
    this.modalService.viewContainerRef = this.viewContainerRef;
  }
}

This pull request pertains to a comparable situation that may catch your interest https://github.com/angular/angular/pull/9393

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 trouble with triggers: Unable to locate the module 'csv-parse/sync' for parsing

Currently, I am utilizing Firebase functions to create an API that is capable of parsing CSV files. However, whenever I attempt to utilize csv-parse/sync instead of csv-parse, my deployment to Firebase Functions encounters a failure with the subsequent er ...

TypeScript - ESBuild - Encountered an unexpected '<' token

When compiling TypeScript files for a React app with esbuild, everything goes smoothly. However, upon checking the browser console, an error pops up: An unexpected token '<' is causing errors after the return statement // components/editor/ ...

Creating and verifying variables in a template

I'm currently exploring how to assign a variable when a specific value/string is identified in an ngFor loop, and then exhibit a div within the same template upon identification... When the condition indicated in the code snippet below holds true, I ...

Tips for customizing the list of components and attributes for each component in the Angular Form.io builder

I have successfully integrated form.io with Angular 10. After creating a demo project using form.io in the Angular CLI, I was able to develop a custom component and customize the editForm for it. import { Injector } from '@angular/core'; import ...

Connecting an Angular 4 Module to an Angular 4 application seems to be causing some issues. The error message "Unexpected value 'TestModule' imported by the module 'AppModule'. Please add a @NgModule annotation" is

Update at the bottom: I am currently facing a massive challenge in converting my extensive Angular 1.6 app to Angular 4.0. The process has turned into quite a formidable task, and I seem to be stuck at a specific point. We have a shared set of utilities th ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Angular - calculate the total of numerical values within a nested *ngFor loop

Looking to extract numerical values from an array of objects, where each object contains specific data within arrays. I attempted using *ngFor to iterate through the values, but instead of summing them up, they are concatenated together. Here's a brie ...

Struggling with configuring internationalization in NestJS

Currently, I am working on a NestJS project where my lead assigned me the task of returning different errors to the frontend based on the language in the request header. After some research, I decided to use i18n for this purpose. However, when testing it ...

Error display in Elastic Apm Rum Angular implementation

Having some issues with incorporating the @elastic/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5948598d8878098d8949b9280999487b5c7dbc4dbc4">[email protected]</a> package into my project. Angular is throwing console ...

How to achieve dynamic class instantiation through constructor injection in Angular 8?

Despite my efforts to find a solution, my understanding of Dependency Injection in services is still limited, making it challenging to get this thing working. I'm left wondering if there's any way to make it work at all. My current setup involve ...

Forcing locale in Angular 2: A step-by-step guide

I recently developed a compact application with Angular2 and incorporated the currency pipe. I noticed that the currency is automatically formatted based on my browser's language. Is there a way for me to customize or override this default behavior? ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

A guide to setting a file size limit for image uploads (e.g. limiting to 2MB) using Angular

We are currently working on implementing a maximum size limit of 2mb for images using ng2-file-upload. Below is the code snippet: uploader: FileUploader = new FileUploader({ url: URL, disableMultipart: true }); ... ... OnFileSelected(event) { ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...

Jasmine encountered an error while trying to compare the same string: 'Expected the values to match.'

I'm encountering an error message, despite verifying that the strings are identical: Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'ty ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Testing Angular2 / TypeScript HTTPService without Mocking: A Guide

import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; @Injectable() export class HttpService { result: any; constructor(private http:Http) { } public postRequest(){ return this.http.get('h ...

ESLint not functioning properly on TypeScript (.ts and .tsx) files within Visual Studio Code

After installing the ESLint extension in VSC, I encountered an issue where it was no longer working on the fly for my React project when I introduced Typescript. In the root of my project, I have a .eslintrc file with the following configuration: { "pa ...

When the draw event in Leaflet's map is finished, activate the Angular Material dialog

I'm looking to activate an Angular Material dialog when the Leaflet draw's draw:drawstop event takes place. How can I ensure that Leaflet events occur within Angular's zone or how can I monitor Leaflet's changes (outside of Angular&apos ...