【问题标题】:Angular Render link角度渲染链接
【发布时间】:2018-06-26 20:21:26
【问题描述】:

我正在使用一个名为ag-grid 的库,它允许我创建一个数据表。在此表中,我通过routerLink 包含指向用户个人资料的链接。

我的问题是,如果用户在搜索中无效,该链接会将您带到无效的个人资料,因此我正在尝试针对这种情况使用不同的链接。

我创建了一个组件来生成我需要的链接,但它只是将 HTML 打印到页面。

组件:

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

@Component({
  template: "{{ link }}"
})

export class ViewLinkComponent {

  params: any;
  link: any;

  agInit(params: any): void {

    this.params = params;

    // If we don't have an NTID, we can assume this is an invalid record
    if (this.params.data.QID == '-') {

      // Loop over our data object
      for (var key in this.params.data) {

        if (this.params.data.hasOwnProperty(key)) {
          // If we are not looking at order and our values are not empty
          if (key != 'order' && this.params.data[key] != '-') {
            this.link = this.createLink(this.params.data[key]);
            return;
          }

        }

      }

    }else{
      this.link = '<a routerLink="/profile/'+ params.data.NTID +'">View Profile</a>'
    }

  }

  createLink(query){
    return '<a href="https://external.com/search?q='+query+'" target="_blank">Search</a>';
  }

}

最终结果:

下图显示了正确的链接,但并未将其呈现为实际的可点击链接。

但是,如果我要执行以下操作,则效果很好:

@Component({
  template: "<a routerLink='/profile/{{ params.data.NTID }}'>View Profile</a>"
})

问题是我需要使用一些逻辑来确定它是使用路由的内部链接还是外部链接。

我有没有办法告诉这个组件它可以渲染那个 HTML,假设它是一个安全的东西?

【问题讨论】:

    标签: angular typescript components ag-grid


    【解决方案1】:

    生成原生 HTML 代码的常用方法是Renderer2。但是,RouterLink 是一个指令,如果您在运行时生成链接,则不会考虑它。 您不能像这样绕过条件模板:

    <a *ngIf="isUserValid" routerLink="/profile/...
    <a *ngIf="!isUserValid" href="https://external.com/search...
    

    【讨论】:

    • 谢谢,我完全忘记了使用ngIf 来拥有两组逻辑。这帮助我解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2015-08-04
    • 1970-01-01
    • 2014-11-09
    相关资源
    最近更新 更多