问题一、 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 = '';
}