はじめに
仕事でAngularを使ってアプリケーションを作成している時に、window.open()
で別ウィンドウを表示する要件があったので、備忘録としてプライデートでも似たような実装をしてみました。
環境
SPAフレームワークのAngularを使用しています。
- Angular: 8.2.14
- Node: 12.13.1
作ったもの
サンプルとして、親ウィンドウの「マトリクス図を開く」ボタンを押下すると新規ウィンドウとしてマトリクス画面(子ウィンドウ)を開くアプリケーションを作りました。
実装
サンプルアプリケーションの実装について順を追って説明していきます。
ルーティング設定
まずルーティングの設定から説明します。親(top
)、子(matrix
)のルーティングを下記の通り設定しました。
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TopComponent } from './component/top/top.component'; import { MatrixComponent } from './component/matrix/matrix.component'; const routes: Routes = [ { path: '', component: TopComponent, pathMatch: 'full' }, { path: 'top', redirectTo: '' }, { path: 'matrix', component: MatrixComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
親ウィンドウの実装
親ウィンドウの実装について説明します。ボタンを押下した時に呼び出されるopenMatrix()
メソッドで、window.open()
に子ウィンドウのルーティングURLを設定して別ウィンドウとして子ウィンドウであるマトリクス画面を表示しています。
top.component.html
<div class="wrapper"> <button (click)="openMatrix()">マトリクス図を開く</button> </div>
top.component.ts
import { Component, OnInit } from '@angular/core'; /** * 親ウィンドウコンポーネント * * @export * @class TopComponent * @implements {OnInit} */ @Component({ selector: 'app-top', templateUrl: './top.component.html', styleUrls: ['./top.component.scss'], }) export class TopComponent implements OnInit { constructor() {} ngOnInit() {} /** * 別ウィンドウでマトリックス画面を開く * * @memberof TopComponent */ public openMatrix() { const rootPath = window.location.origin + window.location.pathname; window.open(rootPath + 'matrix', '_blank', 'location=no,scrollbars=yes'); } }
子ウィンドウの実装
子ウィンドウ(マトリクス画面)については、特別な実装が必要ないので説明を省略します。
データの受け渡しについて
本サンプルアプリケーションでは、親ウィンドウから子ウィンドウへのデータの受け渡しは実施していませんが、仕事で作ったアプリケーションではlocalStorage
を使って、データの受け渡しを実現しました。
実装方法としては、親ウィンドウ側でlocalStorage.setItem()
でデータを格納し、子ウィンドウ側でlocalStorage.getItem()
でデータを取得することで親ウィンドウからデータを受け取るといった感じで実装しています。