在另一个Angular 2应用程序中嵌入一个Angular 2应用程序

时间:2016-11-07 08:06:40

标签: angular iframe embed

我的任务是实现一个基于角度2的应用程序 提供标题,导航栏和页脚。所有非常标准的东西。 但是在导航栏之间,其他角度2的应用程序都可以 显示,哪个应用程序取决于导航中的用户选择 酒吧。 嵌入式Angular 2应用程序可通过自己的URL访问。 导航栏是使用a的结果动态构建的 REST API允许轻松配置。

听起来这可以使用IFRAME来实现,但是在那里 使用IFRAME的任何替代方案,以及使用该方法导航时会发生什么 浏览器的来回按钮,键盘快捷键等。

我可以动态调整IFRAME大小以适应嵌入的大小 角度应用?即使嵌入式应用程序的大小发生变化?

1 个答案:

答案 0 :(得分:0)

使用IFrame可以实现嵌入角度2应用程序或任何其他内容:

import {Component, OnInit, ElementRef, ViewChild} from "@angular/core";
import {NavigationService} from "../navigation.service";
import {ActivatedRoute} from "@angular/router";

@Component({
    selector: 'framed-content',
    template: `
    <div class="row content application-box">
      <div class="col-xs-12 col-sm-12 col-md-12">
        <iframe #iframe style="width: 100%;height: 100vh;position: relative;"
                [src]="selectedContent | safe"
                frameborder="0"
                allowfullscreen></iframe>
      </div>
    </div>
    `
})
export class FramedContentComponent implements OnInit {
    @ViewChild('iframe') iframe: ElementRef;

    private selectedContent = 'content/home.html';

    constructor(private route: ActivatedRoute, private navigationService: NavigationService) {
    }

    /**
     * Registers a callback for retrieving the target based on the selected content
     */
    ngOnInit() {
        this.route.params.map(params => params['selectedItem']).subscribe((selectedItem) => {
            this.selectedContent = this.navigationService.getNavigationItem(selectedItem).target;
        })
    }
}

唯一的问题是调整IFrame的大小以适应内容。 这是通过在容器应用程序的de main index.html中使用一段简单的javascript来解决的:

<script language="JavaScript1.5">
    window.addEventListener('message', function(event) {

        // IMPORTANT: Check the origin of the data!
        if (~event.origin.indexOf('http://localhost')) {
            // The data sent with postMessage is stored in event.data
            console.log(event.data);
            resize(event.data);
        } else {
            // The data hasn't been sent from your site!
            return;
        }
    });

    function resize(frameHeight) {
        console.log('Parent resize');
        frame=document.getElementById('loketFrame');
        console.log(frame);
        frame.height=frameHeight;
    }
</script>

每次嵌入式应用程序更改其大小时,都需要向容器发布消息以更新iframe的高度:

ngOnInit() {

  setTimeout(() => {
    var height = document.documentElement.scrollHeight;
    console.log('Resizing to ' + height);
    parent.postMessage(height, '*');

  }, 0);
}