Angular 渲染 link

Angular Render link

我正在使用一个名为 ag-grid 的库,它允许我创建 table 数据。在此 table 中,我通过 routerLink.

将 link 添加到用户个人资料中

我的问题是,如果用户在搜索中无效,link 会将您带到无效的配置文件,因此我正在尝试针对这种情况使用不同的 link。

我创建了一个组件来生成我需要的 link,但它只是将 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>';
  }

}

最终结果:

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

但是,如果我执行以下操作,它会呈现良好的效果:

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

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

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

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

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