Angular v4のUpgradeModuleを使ってAngularJS v1アプリとのハイブリッドアプリを動作

Angularのバージョン4でAngularJS v1とAngularのv4のアプリを混在させて動作させる方法を確認しました。
 
以下の記事でAngularJS v1のアプリをAngular v4で動作させるサンプルを作成しましたが、そのサンプルアプリをベースにして作成しています。
Angular v4のUpgradeModuleを使ってAngularJS v1アプリを動作
 
※なお、サンプルコードはAngularの4.4.3版、TypeScriptを使って確認したものです。

※目次をクリックすると目次の下部にコンテンツが表示されます。

サンプルコードコードの説明
1)Angular v4のコンポーネント
 
○NgIfComponent
・クラス名:NgIfComponent
・ファイル名:u_ngif.component.ts
・cssセレクタ:<my-ngif>
 
○NgSwitchComponent
・クラス名:NgSwitchComponent
・ファイル名:u_ngswitch.component.ts
・cssセレクタ:<my-ngswitch>
 
2)AngularJS v1のコントローラ内でAngular v4のコンポーネントを使用
 
①ビューに追加

<div ng-controller="bindingCtrl">
・・・・
  <my-ngif>loading...</my-ngif>
  <my-ngswitch>loading...</my-ngswitch>
</div>

 
②AngularJS v1のモジュール定義に追加
 
AngularJS v1のモジュール定義のディレクティブ設定にv4のコンポーネントをdowngradeComponent()メソッドを使って定義。

import { downgradeComponent } from '@angular/upgrade/static';
import { NgSwitchComponent } from './u_ngswitch.component.ts';
import { NgIfComponent } from './u_ngif.component.ts';

angular.module('mainModule', [])
  .directive(
      'myNgswitch',
      downgradeComponent({ component: NgSwitchComponent }) as angular.IDirectiveFactory
  )
  .directive(
      'myNgif',
      downgradeComponent({ component: NgIfComponent }) as angular.IDirectiveFactory
  )

 
3)Angular v4のモジュール設定を修正
 
v4のコンポーネントをdeclarations属性とentryComponents属性に追加します。

@NgModule({
  imports: [
    BrowserModule,
    UpgradeModule,
    FormsModule
  ],
  declarations: [
    NgSwitchComponent,
    NgIfComponent
  ],
  entryComponents: [
    NgSwitchComponent,
    NgIfComponent
  ]
})

 
4)アプリの起動
 
参考記事と同様。

export class AppModule {
  constructor(private upgrade: UpgradeModule) { }
  ngDoBootstrap() {
    this.upgrade.bootstrap(document.body, ['mainModule']);
  }
 }

platformBrowserDynamic().bootstrapModule(AppModule);

デモ
Angular : 4.4.3
Bootstrap : 3.x

こちらをクリック。

<html>
  <head>
    <script src="https://unpkg.com/angular@1.6.4/angular.min.js"></script>
    <script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
    <script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
    <script src="./js/systemjs.config.js"></script>
    <script>
      System.import('./ts/hyb.ts').catch(function(err){ console.error(err);  });    </script>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <link rel="stylesheet" href="./css/styles.css">
  </head>
  <body>
    <div ng-controller="bindingCtrl"><br />
      <strong>1)v1:Wayデータバインディング</strong><br />
      <div>1)二重波括弧:私は{{country}}在住です。</div>
      <div>2)ng-bind:私は<span ng-bind="country"></span>在住です。</div>
      <div>3)二重波括弧:私は{{country}}在住の{{gender}}です。</div>
      <div>4)ng-bind-template:私は{{country}}在住の{{gender}}です。</div>
      <div ng-non-bindable>二重波括弧{{....}}を表示するには、ng-non-bindableを使用。</div>
      <strong>2)v1:2Wayデータバインディング</strong><br />
      <div>私の名前は{{name}}です。</div>
      名前:<input ng-model="name" /><br />
      <strong>3)v4:ngSwitchを使ったサンプル</strong><br />
      <my-ngswitch>loading ngswitch...</my-ngswitch><br />
      <strong>4)v4:ngIfを使ったサンプル</strong><br />
      <my-ngif>loading ngif...</my-ngif>
    </div>
  </body>
</html>

(systemjs.config.js)
(function (global) {
  var ngVer = '@4.4.3';
  System.config({
    transpiler: 'ts',
    typescriptOptions: {
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true,
      "strict": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      'npm:': 'https://unpkg.com/'
    },
    map: {
      'app': 'app',
      '@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
      '@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
      '@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
      '@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs@5.0.1',
      'tslib':                     'npm:tslib/tslib.js',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.3.2/lib/typescript.js',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts',
        meta: {
          './*.ts': {
            loader: 'systemjs-angular-loader.js'
          }
        }
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });

})(this);

●メイン(hyb.ts)
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Component } from '@angular/core'; import { UpgradeModule } from '@angular/upgrade/static'; import { FormsModule } from '@angular/forms'; import { NgSwitchComponent } from './u_ngswitch.component.ts'; import { NgIfComponent } from './u_ngif.component.ts'; import { downgradeComponent } from '@angular/upgrade/static'; angular.module('mainModule', []) .directive( 'myNgswitch', downgradeComponent({ component: NgSwitchComponent }) as angular.IDirectiveFactory ) .directive( 'myNgif', downgradeComponent({ component: NgIfComponent }) as angular.IDirectiveFactory ) .controller("bindingCtrl", function ($scope) { $scope.country = "日本"; $scope.gender = "男性"; $scope.name = "初期値"; }); @NgModule({ imports: [ BrowserModule, UpgradeModule, FormsModule ], declarations: [ NgSwitchComponent, NgIfComponent ], entryComponents: [ NgSwitchComponent, NgIfComponent ] }) export class AppModule { constructor(private upgrade: UpgradeModule) { } ngDoBootstrap() { this.upgrade.bootstrap(document.body, ['mainModule']); } } platformBrowserDynamic().bootstrapModule(AppModule); ●v4コンポーネント(u_ngswitch.component.ts)
import { Component } from '@angular/core'; class Member { name: string; age: number; address: string; } @Component({ selector: 'my-ngswitch', template:` <strong>NgSwitchを使って内部にあるHTMLの表示を切り替え</strong><br /> <input type="button" value="リストを表示" (click)="switch='list'"> <input type="button" value="テーブルを表示" (click)="switch='table'">  <br /> <div [ngSwitch]="switch"> <div *ngSwitchCase="'table'"> <table class="table"> <thead> <tr><th>名前</th><th>年齢</th><th>住所</th></tr> </thead> <tbody> <tr *ngFor="let member of members;"> <td>{{member.name}}</td> <td>{{member.age}}</td> <td>{{member.address}}</td> </tr> </tbody> </table> </div> <div *ngSwitchCase="'list'"> <ul> <li *ngFor="let member of members;">{{member.name}} ({{member.age}}) {{member.address}}</li> </ul> </div> <div *ngSwitchDefault> 上のボタンで選択したフォーマットでデータが表示されます。 </div> </div> ` }) export class NgSwitchComponent { public members = MEMBERS; } var MEMBERS: Member[] = [ ・・・ ]; ●v4コンポーネント(u_ngif.component.ts)
import { Component } from '@angular/core'; @Component({ selector: 'my-ngif', template: ` <strong>NgIfを使って表示、非表示を切り替え</strong><br /> <div class="checkbox"> <label> <input type="checkbox" [(ngModel)]="detail" />詳細表示 </label> </div> <ul> <li *ngFor="let member of members">{{member.name}} <div *ngIf="detail"> <ul> <li>年齢:{{member.age}}</li> <li>住所:{{member.address}}</li> </ul> </div> </li> </ul> ` }) export class NgIfComponent { public members = MEMBERS; } var MEMBERS: Member[] = [ ・・・ ];

関連記事の目次

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください