Angular 2:当路由器url发生变化时更新iframe src

时间:2017-03-18 11:18:39

标签: angular iframe

App有一个顶部栏,上面有3个仪表板按钮。每个链接都会通过iframe在页面上打开一个新的信息中心。
app.component.html

<md-toolbar class="toolbar">
  <span>Dashboardds</span>
  <span class="spacer"></span>
  <button md-button  [routerLink]="['/dashboard', 'first']"  id="first" class="top-link">First</button>
  <button md-button  [routerLink]="['/dashboard', 'second']"  id="second" class="top-link">Second</button>
  <button md-button  [routerLink]="['/dashboard', 'third']"  id="third" class="top-link">Third</button>
</md-toolbar>
<router-outlet></router-outlet>

app.module.ts

{path: 'dashboard/:id', component: DashboardComponent},
{path: '', redirectTo: 'dashboard/first', pathMatch: 'full'},
{path: '**', redirectTo: 'dashboard/first', pathMatch: 'full'}

仪表板组件非常简单。它有3个网址和1个iframe。
dashboard.component.html

export class DashboardComponent implements OnInit, OnChanges {
dashboardUrl: SafeUrl;
  first_url: string = "first url of the dashboard";
  second_url:string="second url of the dashboard";
  third_url:string="third url of the dashboard";


  constructor(private route: ActivatedRoute, private sanitizer: DomSanitizer) {
    //console.log("Constructor "+route.snapshot.params['id']);
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_south_url);
  }

  ngOnInit() {
    this.dashboardUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.first_south_url);
  }

  ngOnChanges(changes: SimpleChanges){
  }
}

dashboard.component.html

<iframe id="report-frame" frameborder="0" [src]="dashboardUrl"></iframe>

如何根据顶部栏上点击的按钮更新iframe网址并使用新网址重新加载iframe?

1 个答案:

答案 0 :(得分:2)

您应该在dashboard.component.ts文件中订阅ActivatedRoute对象以获取路线中的更改并更新iframe。为了避免在设置iframe目标时出现不安全的值错误并保持代码清洁,您应该在管道中使用DomSanitizer

<强> safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(
    private sanitizer: DomSanitizer
  ) { }

  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

另外,不要忘记将SafePipe添加到AppModule的声明

<强> dashboard.component.ts

export class DashboardComponent implements OnInit {
  private dashboardUrl: string;
  private urlMap: { local: string, remote: string }[] = [
    { local: "first", remote: "http://google.com" },
    { local: "second", remote: "http://stackoverflow.com" }
    // ...
  ];

  constructor(
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      let localParam = params['id'];
      this.dashboardUrl = this.urlMap.filter(x => x.local == localParam)[0].remote;
    });
  }
}

<强> dashboard.component.html

<iframe id="report-frame" frameborder="0" [src]="dashboardUrl | safe"></iframe>