2017-03-18 155 views
0

應用程序有一個帶3個儀表板按鈕的頂部欄。每個鏈接通過iframe在頁面上打開一個新的儀表板。
app.component.htmlAngular 2:更新路由器url獲取更改時的iframe src

<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

您應該在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> 
+0

我需要的'app.component.html'頁面上改變什麼? –

+0

不,它應該沒問題。 :) –