iframe高度自适应里面html内容的高度

在Angular中,要确保iframe的高度一定大于加载的外部HTML内容的高度,你可以使用Angular的HostListener和Renderer2来实现动态设置iframe的高度。

首先,在组件类中引入Renderer2和ViewChild:

 

typescript

import { Component, Renderer2, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

然后在组件类中使用ViewChild来获取iframe元素,并使用Renderer2来动态设置iframe的高度:

typescript

export class YourComponent implements AfterViewInit {
  @ViewChild('iframe') iframe: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    this.adjustIframeHeight();
  }

  @HostListener('window:resize', ['$event'])
  onResize(event: Event) {
    this.adjustIframeHeight();
  }

  adjustIframeHeight() {
    const iframeElement = this.iframe.nativeElement;
    if (iframeElement) {
      const contentHeight = iframeElement.contentWindow.document.body.scrollHeight;
      this.renderer.setStyle(iframeElement, 'height', contentHeight + 'px');
    }
  }
}

在模板文件中,使用ViewChild给iframe添加一个标识符,并绑定src属性:

html

<iframe #iframe [src]="'your_external_html_url'"></iframe>

上述代码中,adjustIframeHeight函数会在组件初始化后和窗口resize事件时被调用,它会获取iframe内部内容的高度,并将iframe的高度设置为内容高度,从而保证iframe的高度一定大于加载的外部HTML内容的高度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值