微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular6 iframe应用

问题一、 iframe如何自适应屏幕高度

解决思路:通过设置iframe外层父元素高度等于window高度,再相对于父元素定位iframe元素;案例如下:

第一步: 模板文件中使用iframe

// demo.component.html
<div style="position: relative; " [style.height]="outHeight">
    <iframe [src]="srcValue" allowtransparency="true" frameborder="0" id="defaulIframePage" style="position: absolute; width: 100%; height: 100%; "></iframe>
</div>

第二步: ts 中自定义iframe外层父元素的高度

// demo.component.ts
import {fromEvent} from "rxjs/index";

export class DemoComponent imple implements OnInit{

   srcValue = ‘http://www.baidu.com‘;  
   outHeight = ‘0px‘;

   ngOnInit() {
      // ifram最外层高度
      this.outHeight = window.innerHeight + ‘px‘;
      fromEvent(window,‘resize‘).subscribe(($event) => {
          this.outHeight = window.innerHeight + ‘px‘;
      });
  }
}

问题二、 安全机制设置

错误

分享图片

解决

第一步:创建管道

import { Pipe,PipeTransform } from ‘@angular/core‘;
import {DomSanitizer} from "@angular/platform-browser";

@Pipe({
  name: ‘safe‘
})
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(value: any,args?: any): any {
      return this.sanitizer.bypassSecurityTrustResourceUrl(value);
  }
}

第二步: 在demo.component.html文件中加入管道

<iframe [src]="item.url | safe" allowtransparency="true" frameborder="0" id="defaulIframePage" style="position: absolute; width: 100%; height: 100%; "></iframe>

问题三、src值为同域名不同参数时,iframe不刷新问题

解决思路:使用动态组件 - 将iframe放至动态组件中,父组件将src传值给动态组件,并且每次传值时动态渲染组件;

1. 父组件定义

// parent.component.html
<a href= "javascript:;" (click)="loadCmp(srcArray[1])">切换iframe的src值</a>
<div #dynamic></div>



// parent.component.ts
export class ParentComponentimplements OnInit,OnDestroy {

    
    // 动态切换的src模拟数据
    srcArray = ["index.html?id=‘11‘","index.html?id=‘22‘"];

    // 动态组件
    @ViewChild(‘dynamic‘,{ read: ViewContainerRef }) dmRoom: ViewContainerRef;
    currentCmp: any; // 当前渲染组件

    constructor(private cfr: ComponentFactoryResolver) {}

   ngOnInit() {
        // 动态渲染组件
        this.loadCmp(this.srcArray[0]);
    }



    // 动态渲染组件方法
    loadCmp(srcValue) {

        const com = this.cfr.resolveComponentFactory(DynamicComponent);
        this.dmRoom.clear(); // 清空视图
         this.currentCmp = this.dmRoom.createComponent(com);

        // 传值
         this.currentCmp.instance.pathUrl = srcUrl;

    }     
}

2. 动态组件定义

// dynamic组件;;别忘记将DynamicComponent加入数组entryComponents中;
// dynamic.component.html
<iframe [src]="pathUrl | safe" allowtransparency="true" frameborder="0" id="defaulIframePage" style="position: absolute; width: 100%; height: 100%; "></iframe>

// dynamic.component.ts
export class DynamicComponent {
  pathUrl: string = ‘‘;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐