【问题标题】:Angular: Rendering and Getting the HTML of a Component DynamicallyAngular:动态渲染和获取组件的 HTML
【发布时间】:2020-01-31 23:45:04
【问题描述】:

渲染组件的 HTML,以便它可以用于打开 about:blank 类型的新选项卡(与应用程序本身无关的空白新 html 页面)。

为什么? 为了避免使用字符串变量创建 HTML,例如:

var html = '<div>
              <h3>My Template</h3>
              ' + myProperty + ' 
            </div>';

我看到您可以使用ViewContainerRef.createComponentComponentFactoryResolver 动态呈现组件。这样做的问题是组件在应用程序中的视图容器内呈现。我想做的是生成该组件的 HTML,这样我就可以使用该 HTML 将它放在我想要的任何地方。 (在这种情况下,在window.open() 方法给出的对象的文档属性中)

示例:

@Component({
  selector: 'app-component',
  template: `
            <div>
              <h3>My Template</h3>
              {{ myProperty }}
            </div>
          `,
  styleUrls: ['./my.component.less']
})
export class MyComponent{
  myProperty: string;
}

我希望以这种方式使用它:

//get new window tab
var newTab = window.open('about:blank', '_blank');

//get the HTML of the component

//use it to open the new tab
newTab.document.write(html);

【问题讨论】:

标签: html angular typescript components angular8


【解决方案1】:

它可能对其他人有所帮助,所以我在这里发布我所做的以及我发现的问题。在寻找一些解决方案后,this one 为我工作。问题是我意识到 Angular 会清理您的 HTML,删除所有可能的 &lt;script&gt; 标签。不幸的是,我喜欢其中的 3 个。此外,如果您不希望对它们进行清理,则必须使用名为 DomSanitizer 的服务并使用方法 bypassSecurityTrustScript (doc) 将脚本作为参数传递。所以不要“字符串化”代码的想法已经消失了。话虽如此,我使用了原始方法,将 HTML 存储在一个变量中,然后作为参数传递给window.open

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2018-12-29
    • 1970-01-01
    • 2023-03-14
    • 2021-01-22
    • 2020-03-17
    • 2014-04-26
    • 2021-06-14
    • 2019-08-18
    相关资源
    最近更新 更多