問題一、 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 = '';
}