How to open component in new browser tab in angular from another component

645 Views Asked by At

I want to open a component in new browser tab from another compoent.

Here in my AppComponent html file has a button. when I click on this button I want to open MapComponent.html file in new browser tab. Here after click on it map component is open in new browser tab. but button also showing in new tab. But I don't want to show any HTML file related to the other component in the MapComponent.html file. I want to show only MapComponent data in that tab. how to do it. Thanks.

App-component.html

<button (click)="openMapInNewTab()">Open Map</button>

App-component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'routeApp';

  constructor(private router: Router) {}


  openMapInNewTab() {
    const url = '/map';
    window.open(url, '_blank');
  }
}

Map-component.html

<p>map works!</p>

Map-component.ts

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

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent {

}

**AppModule **

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';

@NgModule({
  declarations: [
    AppComponent,
    MapComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

AppRoutingModule

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MapComponent } from './map/map.component';

const routes: Routes = [
  {path: '', component: MapComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
1

There are 1 best solutions below

2
gentbrika On BEST ANSWER

Solution to it is firstly you need to add <router-outlet> tag so the application can navigate between components, after that i have separated the components so created a new component for button button.component.ts, declared it in routes also. This will solve the issue and here you can find solution