【问题标题】:Angular dynamic component loses style when embedded in iframeAngular 动态组件嵌入 iframe 时会丢失样式
【发布时间】:2021-03-29 21:38:27
【问题描述】:

我需要一个动态组件嵌入到 iframe 中。我见过的唯一方法是使用 createComponent 动态生成给定组件的新实例,然后将其移动到 iframe 的主体中。

这种方法的问题是没有样式继承,因为动态组件是在父页面中生成并复制过来的——但是,样式是在父页面的头部注入的,而不是随之而来。

我的想法是解决这个问题的方法是想出一种方法来手动将生成的样式迁移到 iframe 中,或者以某种方式在 iframe 本身内生成组件,以便在其中呈现样式。

这是一个问题示例:https://stackblitz.com/edit/angular-ivy-ajo1gy?file=src/app/app.component.ts

非常感谢任何建议或想法!感谢收看!

【问题讨论】:

    标签: javascript angular iframe


    【解决方案1】:

    我不知道你是否可以获得与组件相关的样式,所以你只剩下:

    • 创建样式对象(虽然是个坏主意)
    public ngAfterViewInit(): void {
        setTimeout(() => {
          // get reference to loaded iframe document
          this.frameDoc =
          this.contentFrame.nativeElement.contentDocument ||
          this.contentFrame.nativeElement.contentWindow;
          this.frameDoc.body.appendChild(this.contentRef.location.nativeElement);
          const style = document.createElement("style");
          style.innerHTML = `
          h1 {
            color: blue;
          }
          `;
          this.frameDoc.body.appendChild(style);
        }, 1000);
      }
    
    @Component({
      selector: "hello",
      template: `<h1 [style.color]="'blue'">Content Window - I should be blue</h1>`
    })
    export class HelloComponent {}
    
    @Component({
      selector: "hello",
      template: `
        <h1 [ngStyle]="{'color': 'blue'}">Content Window - I should be blue</h1>`,
    })
    export class HelloComponent {}
    

    【讨论】:

    • 我用不同的方法得到了混合的结果,尤其是在不同的浏览器和平台上。最后,我只是在模板本身中使用内联样式,并使用模板插值到需要动态值的 getter。不是最干净的方法,但如果您已经在使用 iframe 隐藏备用模板,我猜您已经陷入困境。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多