Angular2:如何更改iFrame src?

时间:2017-02-13 20:47:20

标签: javascript angular iframe

我是Angular2的新手,并尝试通过点击按钮更改iframe的网址。通过了safe urlsetting the src for iframe等几个障碍。无法想出一个很好的方法来点击按钮/链接更改网址。
如何根据按钮ID更改iFrame网址?
HTML

<button md-button (click)="updateSrc($event)"  id="first" class="top-link">First</button>
  <button md-button  (click)="updateSrc($event)" id="second" class="top-link">Second</button>

<iframe id="frame" frameborder="0" [src]="changeUrl()"></iframe>

组件

private first_url = "some url";
private second_url = "some other url":

updateSrs(event) {
    console.log('Here');
    console.log(event.currentTarget.id);
    this.reportUrl();
  }
;
  changeUrl() {
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.first_url);
  }

1 个答案:

答案 0 :(得分:6)

无需处理事件,因为您可以从模板中访问组件属性...

模板:

<button md-button (click)="updateSrc(first_url)"  id="first" class="top-link">First</button>
<button md-button  (click)="updateSrc(second_url)" id="second" class="top-link">Second</button>

<iframe id="frame" frameborder="0" [src]="current_url"></iframe>

ts:

first_url = "some url";
second_url = "some other url":
current_url: SafeUrl;


updateSrc(url) {
    this.current_url=this.sanitizer.bypassSecurityTrustResourceUrl(url)
  }