iframe内的Angular 2触发插值

时间:2016-05-31 15:52:22

标签: iframe angular

我想在iframe中显示模板化网页的内容。但是在加载内容之后,模板不会通过角度进行插值。是因为变化检测系统?可以通过其他方式实现吗?

@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 个答案:

答案 0 :(得分:8)

你应该使用[srcdoc]

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

传递内容你应该使用DomSanitizationService来传递脚本,形成elemet。

constructor(private sanitizer: DomSanitizationService) {}

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

请参阅https://angular.io/docs/ts/latest/guide/security.html#!#xss

答案 1 :(得分:1)

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

Interplation仅由直接添加到模板的HTML和绑定触发。

您可以在<iframe>中加载不同的Angular应用程序,并使用postMessage在主应用程序和<iframe>

之间传递数据

如果仅用于一次性插值,则可以使用TypeScripts字符串插值,如

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);
  }
}