Angular 2如何在iframe中触发插值表达式

5

我想在iframe中显示一个模板化网页的内容。但是在加载内容后,模板没有被Angular插值。这是因为变更检测系统吗?还有其他可以实现的方法吗?

@Component({
  selector: 'my-app',
  template : `<iframe [src]="template" width="100%" height="300px"></iframe>`
})
export class App {
  template: string = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <title>Page title</title>

      </head>
      <body>
        <p>{{strings[0]}}</p>
        <p>{{strings[1]}}</p>
        <p>{{strings[2]}}</p>
      </body>
    </html>
  `;
  strings: string[] = ['first element', 'second element', 'third element'];
  constructor(){
    this.template = 'data:text/html;charset=utf-8,' + encodeURI(this.template);
  }
}

bootstrap(App)

http://plnkr.co/edit/mWrqv1?p=preview

使用innerHtml绑定也似乎不起作用:

@Component({
  selector: 'my-app',
  template : `<div [innerHtml]="template"></div>`
})
export class App {
  template: string = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <title>Page title</title>

      </head>
      <body>
        <p>{{strings[0]}}</p>
        <p>{{strings[1]}}</p>
        <p>{{strings[2]}}</p>
      </body>
    </html>
  `;
  strings: string[] = ['first element', 'second element', 'third element'];

}

bootstrap(App)

http://plnkr.co/edit/wscpSR?p=preview

2个回答

8

你应该使用[srcdoc]

template: `<iframe id="{{patternId}}" [srcdoc]="srcdoc" > </iframe>`,

要传递内容,您应该使用DomSanitizationService来能够传递脚本、表单元素。

constructor(private sanitizer: DomSanitizationService) {}

ngOnInit():any {
this.srcdoc = this.sanitizer.bypassSecurityTrustHtml(this.data.patternSource);
}

请查看{{link1}}


构造函数(private sanitizer: DomSanitizer){ - Meetai.com

1

[src]="template"[innerHtml]="template"通常不会触发任何插值或组件或指令实例化。因此,您所描述的行为是预期的并且是经过设计的。

插值仅通过直接添加到模板的 HTML 和绑定来触发。

您可以在<iframe>中加载不同的 Angular 应用程序,并使用postMessage在主应用程序和<iframe>之间传递数据。

如果仅涉及一次性插值,您可以使用TypeScript字符串插值,例如

export class App {
  template: string = `
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <title>Page title</title>

      </head>
      <body>
        <p>${strings[0]}</p>
        <p>${strings[1]}</p>
        <p>${strings[2]}</p>
      </body>
    </html>
  `;
  strings: string[] = ['first element', 'second element', 'third element'];
  constructor(){
    this.template = 'data:text/html;charset=utf-8,' + encodeURI(this.template);
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接