Having trouble with Angular 4 Portal/CdkPortal not functioning properly in a new child window

I am currently working on an Angular 4 application and I am facing the task of displaying a specific component in a new child window. After researching for a solution (I am not interested in using routing by URL as my server always redirects to index with window.open('some URL')), I came across this helpful example on StackBlitz: StackBlitz Example

In the provided example, they are utilizing CdkPortal. However, I encountered an issue as it seems cdk portal is not available in angular 4 (an error message stating '

@angular/cdk/portal"' has no exported member 'CdkPortal'
was displayed).

Although I attempted to replicate the same example since it perfectly aligns with my requirements, it doesn't seem to work with my angular version.

Is there an equivalent example that can be used for Angular 4?

ADDITIONAL

The example includes a code snippet to display the window:

<window *ngIf="showPortal">
  <h2>Hello world from another window!!</h2>
  <button (click)="this.showPortal = false">Close me!</button>
</window>

This raises the question if it's possible to add another component within the main component being attached in the portal. For instance:

<window *ngIf="showPortal">
  <my-other-component [currentValue]="someValue"></my-other-component>
</window>

If such functionality is achievable, will the added component function correctly?

Answer №1

Here is a solution to generate a child window without using CdkPortal.

The method used here involves the generic window.open() function to open a new window and utilizing the name property of the window to reference the opened window.

In app.component.ts:

import { Component,ComponentFactoryResolver, ViewChild, ViewContainerRef,Injector } from '@angular/core';
import { DynamicWindowComponent } from './dynamic-window/dynamic-window.component';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  injector: Injector;
  OpenWindow : any

  constructor(private resolver: ComponentFactoryResolver) { }

  open(): void {
    const componentFactory = this.resolver.resolveComponentFactory(DynamicWindowComponent);
    let componentRef  = componentFactory.create(this.injector);
    this.OpenWindow = window.open('', 'childwindow', 'width=400,height=400,left=150,top=200');
    this.OpenWindow.document.body.innerHTML = "";
    this.OpenWindow.document.body.appendChild(componentRef.location.nativeElement);
  }

  close(){
    this.OpenWindow.close()
  }
}

In app.component.html:

<button (click)="open()">Dynamically Add Component</button>

In dynamic-window.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dynamic-window',
  templateUrl: './dynamic-window.component.html',
  styleUrls: ['./dynamic-window.component.css']
})
export class DynamicWindowComponent{
  close(){
    // get reference of child window by its name and close it
    let existingWin = window.open('', 'childwindow');
    existingWin.close();
  }
}

In dynamic-window.component.html:

<p>Dynamic Component</p>
 <button (click)="close()">Close me!</button>

For a working example, you can check the link below:

https://stackblitz.com/edit/angular-rbapx4?embed=1&file=src/app/app.component.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

The information in the map cannot be inferred by Typescript based on the generic key type

I encountered a TypeScript issue while refactoring an existing feature in my app. It seems that TypeScript is having trouble picking up the correct type when passing the generic type through nested functions. enum App { AppOne = 'app-one', A ...

Trouble loading data with ContentChildren when querying RouterLink and RouterLinkWithHref

I've been working on a custom Structural Directive inspired by the functionality of the RouterLinkActive directive. To get started, I followed the example for the UnlessDirective and incorporated elements from Angular's RouterLinkActive directiv ...

creating a toolbar with content using Ionic framework

I currently have a toolbar implemented on my webpage. I want to show different content on the same page based on the user's selection from the toolbar. How can I make use of Ionics to achieve this functionality? <ion-toolbar no-border-top> < ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

A guide on simulating x-date-pickers from mui using jest

I have successfully integrated a DateTimePicker into my application, but I am facing an issue with mocking it in my Jest tests. Whenever I try to mock the picker, I encounter the following error: Test suite failed to run TypeError: (0 , _material.gen ...

Developing a FixedUpdate Function in TypeScript

Currently, I am delving into the world of game-engine development using TypeScript to expand my skills. The fixed update mechanism in Unity operates on a theoretical premise that involves processing physics within a while loop. Here's how it is envisi ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

Encountering issues with `createAsyncThunks` triggering errors in Prettier

I'm encountering errors from Prettier specifically related to the createAsyncThunk code, whereas TypeScript and ESLint do not detect these issues. What could be causing this discrepancy? Error instances include: src\store\slices\calend ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

Dynamically incorporate controls in Angular4.4-RxJs post API data retrieval

I am currently working on creating a form that dynamically adds checkboxes based on data received from an API. After successfully receiving the data in JSON format, it looks like this: [ { "code": "TicketTypeRead", "name": "Read Ticket Types" }, { ...

"Enhance your database with Firebase's dynamic features for adding and removing

Within my firebase database, I have the following data structure: -ActionSheet -PendingApproval -SomeKey1 -someData -someData -someData -SomeKey2 -someData -someData ...

"Exploring the process of passing an observable to map in RxJS

Being new to Angular and RxJS, I am currently working on a pipe function that utilizes several operators. One of the operators includes a 'map' with a ternary condition that can return either an empty array or another observable obtained from an ...

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

Find a Mongoose query that retrieves items where X exists in both arrays, while Y only exists in one array

I am currently constructing a filtering mechanism and have run into a roadblock. It's worth noting that this code is for demonstration purposes only and does not belong to the actual project, but the core idea remains consistent. I have altered the na ...

Tips for retaining mat table paginator on the chosen page even after refreshing the page

Utilizing a mat table to display paginated data fetched from my API presents a challenge when the page is refreshed after the user navigates away. Instead of displaying the initial first page, I aim to show the second page. To achieve this, I store the pa ...

Tips for creating an array that aligns with the keys of a type in TypeScript

Currently, I am utilizing the Kysely SQL builder for JS based on Vercel's recommendation, despite the limited documentation and community support. This SQL builder is fully typed, allowing you to create a db object with a schema that recognizes table ...

Error compiling SCSS in Angular 6 due to a util.js issue

As a novice in the world of Angular 6, I am currently exploring the Angular CLI and trying to grasp the file structure. My goal is to utilize SCSS for creating a unified global stylesheet. However, during compilation, an error keeps popping up: ERROR in . ...

Steps for resetting the TypeScript version in VSCode:

I've recently been immersed in a typescript project using Visual Studio Code. Our project relies on an older version of typescript (1.8.10), which has been working seamlessly so far thanks to having the appropriate ts compiler package installed locall ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

What is the best method for sending ngForm to a child component?

I'm facing a challenge with reusing a custom input component across multiple forms. The issue lies in passing the parent form context to it. While I successfully accomplished this using reactive forms by passing the FormGroup instance and field name, ...