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

The ngIf directive did not initialize the observable in the child component as expected

I'm facing an issue with CompA and CompB in my Angular project. CompA has a child component called CompB, which has an ngIf condition based on an observable that is shared between the two components. When I set this condition to true and call next on ...

What is the process of incorporating a JavaScript node module into TypeScript?

Having trouble importing the xml2js module as I keep getting a 404 error stating that it's not found. import xml2js from 'xml2js'; Any suggestions on how to properly import JavaScript modules located in the node_modules directory when work ...

What is the correct way to declare a variable with a generic type parameter?

Exploring the following code snippet that showcases a React component being defined with a type argument named TRow: function DataTable<TRow> ({ rows: TRow[] }) { return ( ) } Prior to this implementation, ES6 was utilized and components were c ...

Leveraging the power of Angular4 to dynamically iterate through SVG elements with the

Currently, I am utilizing SVG for font-icons and it is performing flawlessly. However, I have encountered a significant issue while employing *ngFor in my code: <ion-col col-3 *ngFor="let land of landscape_amenities> <span class="icon-{{land. ...

I am struggling to delete real-time records in Angular using Firestore

I am facing an issue with my Angular code. I want to be able to delete a record and have it reflect in real-time. When I create a product, it works fine, but deleting the product doesn't work unless I refresh the browser. I'm not sure where the p ...

What is the best arrangement of folders for an enterprise Angular 16 project that ensures both scalability and maintainability over an extended period of time?

Embarking on a significant Angular project with multiple features and modules ahead of me, I find myself in a quandary over the best folder structure to ensure scalability and easy maintenance in the long run. This project will encompass three modules, wi ...

The error message 'ReferenceError: MouseEvent is not defined' indicates that

Recently, I attempted to incorporate ng2-select into a project that relies on angular/universal-starter (TypeScript 2.x) as its foundation. (Interestingly, ng2-select worked perfectly fine when added to an angular-cli generated project.) However, upon ad ...

Angular Object

I am currently working on a small Angular project that focuses on displaying and managing bank accounts using CRUD operations, including transactions. However, I have encountered an issue that is puzzling me. Whenever I click on one of the listed accounts, ...

Steps for setting up multiple tables in an Ionic Angular app using SQLITE

Attempting to create multiple tables in SQLITE within an Ionic project, I've encountered issues with the current format. Can anyone suggest a solution or method for creating multiple tables in SQLITE within an Ionic project? Thank you in advance. fun ...

Is there a way to exclusively view references of a method override in a JS/TS derived class without any mentions of the base class method or other overrides in VS Code?

As I work in VS Code with TypeScript files, I am faced with a challenge regarding a base class and its derived classes. The base class contains a method called create(), which is overridden in one specific derived class. I need to identify all references ...

"Implementing Ionic 2 tabs allows for retrieving the previously selected option with the

Here is the code I am currently working on: onTabsChange(abc) { let selected_tab = this.tabs.getSelected(); let tab_index = selected_tab.index; console.log(tab_index); // should print current tab index but it prints previously selected tab index ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Fetching URL from Right Before Logging Out in Angular 2 Application

I am struggling to capture the last active URL before logging a user out of my Angular 2 app. My goal is to redirect them back to the same component or page once they log back in. Currently, I am using this.router.routerState.snapshot['url'] to r ...

Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Ensuring the accuracy of forms using third-party verification services

While working on an Angular form validation using an external service, I encountered a cannot read property of undefined error. The component contains a simple form setup: this.myForm = this.fb.group({ username: ['', [this.validator.username] ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Expo background fetch initialized but not activated

During the development of my React Native app, I encountered the need to perform periodic background fetches from another server. To achieve this, I utilized two classes from Expo: import * as BackgroundFetch from 'expo-background-fetch'; import ...

How is it that in TypeScript, a potential numeric value in an interface can be transformed into an impossible numeric value in a class implementation?

Encountered a surprising behavior from the TypeScript compiler today. Unsure if it's a bug or intentional feature. If it is indeed intentional, I would like to understand the reasoning behind it. The issue arises when declaring an interface method wi ...

Using jQuery with Angular 4 allows for powerful front-end development

To include jQuery in an Angular4 project, I follow these steps: npm install --save jquery npm install --save-dev @types/jquery In the app.component.ts file import $ from 'jquery'; or import * as $ from 'jquery'; When running "ng se ...