Launch a fresh window in Angular application without the need for a complete restart

How can I open a new window in Angular while passing values in the route to call an endpoint without causing the entire application to reload? It feels like such a hassle just to display a simple HTML page. Is there a better way to achieve this?

Answer №1

If you're looking to create new portals or windows in Angular, consider using Angular's CdkPortal. Creating a simple portal example would involve:

import {Component, ViewChild, OnInit, ComponentFactoryResolver, ApplicationRef, Injector, OnDestroy } from '@angular/core';
import {CdkPortal, DomPortalHost} from '@angular/cdk/portal';

@Component({
  selector: 'app-window',
  template: `
    <ng-container *cdkPortal>
      <ng-content></ng-content>
    </ng-container>
  `
})
export class WindowComponent implements OnInit, OnDestroy {
  @ViewChild(CdkPortal) portal: CdkPortal;
  private externalWindow = null;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private applicationRef: ApplicationRef,
    private injector: Injector){}

  ngOnInit(){
    this.externalWindow = window.open('', '', 'width=600,height=400,left=200,top=200');

    const host = new DomPortalHost(
      this.externalWindow.document.body,
      this.componentFactoryResolver,
      this.applicationRef,
      this.injector
      );

    host.attach(this.portal);
  }

  ngOnDestroy(){
    this.externalWindow.close()
  }
}

Any content enclosed within the <app-window> tags will be passed to the WindowComponent using <ng-content>. For example:

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

@Component({
  selector: 'my-app',
  template: `
    <p>Click this button to open a new window:</p>
    <button (click)="this.showPortal = true">Open Window</button>

    <app-window *ngIf="showPortal">
      <h2>Data from another window.</h2>
      <button (click)="this.showPortal = false">Close Window</button>
    </app-window>
  `,
})
export class AppComponent  {
  showPortal = false;
}

Check out the working example here: Stackblitz

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

Discover the latest Angular edition through coding

Is there a simple way to display my Angular version on a website using code instead of checking it in the command line with 'ng --version'? ...

Removing spaces within brackets on dynamic properties for objects can be achieved by utilizing various methods such as

I've encountered an issue with my code that involves getting spaces within square brackets for the dynamic properties of an object. Even after searching through Code Style/Typescript/Spaces, I couldn't find any settings to adjust this. Could thes ...

The chart is failing to refresh with the latest response information (using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9)

I recently upgraded my project using Chart.js version 3.2.1 and ng2-charts version 3.0.0-beta.9. Initially, everything seemed to be working fine with mock data - the charts were displaying as expected. However, when I switched to testing with real backend ...

Tips for utilizing the JS attribute "offsetWidth" within Angular 4

I am attempting to retrieve the width of an element using JavaScript in my Angular application. document.getElementsByClassName("element")[0].offsetWidth; However, I keep encountering the following compilation error: Property 'offsetWidth' d ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

Receiving the error notification from a 400 Bad Request

I'm having trouble showing the errors returned from an API on my Sign up form when a user submits invalid data. You can check out the error response in the console here: console ss This is my approach in RegisterComponent.ts: onSubmit() { this.u ...

What is the process for declaring global mixins and filters on a Vue class-based TypeScript component?

Recently, I've been working on incorporating a Vue 2 plugin file into my project. The plugin in question is called global-helpers.ts. Let me share with you how I have been using it: import clone from 'lodash/clone' class GlobalHelpers { ...

Utilizing Angular 6 for mapping objects in reactive forms

I'm having trouble mapping the value of my hero object from a Reactive form in Angular. Below is the code snippet from my hero-add.component.ts file: import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../He ...

Utilizing a segment of one interface within another interface is the most effective method

In my current project using nextjs and typescript, I have defined two interfaces as shown below: export interface IAccordion { accordionItems: { id: string | number; title: string | React.ReactElement; content: string | React. ...

Can content projection be utilized from a child component in Angular?

Keep in mind, this example could be achieved without using content projection. I am just showing a simplified version here. Imagine having a component that displays lists of names in two separate elements: import { Component } from '@angular/core&ap ...

Angular 9 library compilation issue: Module unused warning detected

After upgrading my project from Angular 8 to Angular 9, I encountered a warning when trying to build the library: The '__read' is imported from external module 'tslib', but never used https://i.stack.imgur.com/Xg4Eu.png This warning ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...

compileOnSave has ceased to function

After successfully building my ng4 project with "@angular/material": "^2.0.0-beta.6" and having the compileOnSave feature work fine, I decided to add the following dependencies: "@ngx-translate/core": "^8.0.0", "@ngx-translate/http-loader": "^2.0.0", "an ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Encountering an issue upon launching the application: "Error: Token is required in order to proceed!"

I encountered the following error. Can someone please point out what's causing it? How can I resolve this issue? Could there be something missing in main.ts? Error: (index):39 Error: Error: Token must be defined! at new BaseException (https:/ ...

Exploring NestJS: Leveraging the @Body() Decorator to Retrieve Request Body Data

import { Controller, Post, Body } from '@nestjs/common'; import { MyService } from 'my.service'; import { MyDto } from './dto/my.dto'; @Controller('my-route') export class MyController { constructor(private rea ...

Angular D3 - The method 'getBoundingClientRect' is not present in the 'Window' type

Check out this StackBlitz demo I created: https://stackblitz.com/edit/ng-tootltip-ocdngb?file=src/app/bar-chart.ts In my Angular app, I have integrated a D3 chart. The bars on the chart display tooltips when hovered over. However, on smaller screens, th ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

Utilizing TypeScript for enhanced Chrome notifications

I am currently developing a Chrome app using TypeScript (Angular2) and I want to implement push notifications. Here is the code snippet for my notification service: import {Injectable} from 'angular2/core'; @Injectable() export class Notificati ...