首页 > 解决方案 > 如何在按钮单击时将网站加载为 iframe 并将参数传递给 Angular 中的 URL

问题描述

所以我有两个不同的角度项目。一个是登陆页面网站,另一个是出售书籍的网站。

登陆页面组件在其 URL ( http://localhost:8000/landing/RwgnUvDpEicFA5pWF )中有路由参数和一个按钮:

<button type="button" class="btn btn-primary">Buy Books</button>

我希望这个按钮加载另一个网站,书籍作为 iframe 出售,同时在点击时将路由参数传递给它的 URL。

有谁知道我该怎么做?

标签: javascripthtmlangulartypescript

解决方案


你需要做很多步骤才能到达那里。

  1. mouseup为按钮或事件绑定事件处理程序click
  2. 获取当前路由器端点并将其附加到您的 iframe url。
  3. 清理 iframe 网址。
  4. 设置布尔标志以显示 iframe。

零件

import { Component, OnInit, OnDestroy } from '@angular/core';

import { NavigationEnd, Router } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit, OnDestroy {
  iframeUrl: string;
  showIframe = false;
  routerSubscription: any;

  constructor(private _router: Router, private _sanitizer: DomSanitizer) { }

  ngOnInit() {
  }

  public mouseUp(event: any) {
    this.routerSubscription = this._router.events.filter(e => e instanceof NavigationEnd).subscribe(
      event => {
        this.iframeUrl = "url to iframe/" + event['urlAfterRedirects'];
        this.iframeUrl = this._sanitizer.bypassSecurityTrustResourceUrl(this.iframeUrl);
        this.showIframe = true;
      }
    );
  }

  ngOnDestroy() {
    if(this.routerSubscription) {
      this.routerSubscription.unsubscribe();
    }
  }
}

模板

<button type="button" class="btn btn-primary" (mouseup)="mouseUp($event)">Buy Books</button>

<ng-container *ngIf="showIframe">
  <iframe [src]="iframeUrl" width="100%" height="100%" frameBorder="0" scrolling="no">Alternative text</iframe>
</ng-container>

推荐阅读