【问题标题】:Insert anchor tag in string variable在字符串变量中插入锚标记
【发布时间】:2018-01-26 00:15:46
【问题描述】:

我正在尝试在字符串变量中插入锚标记。该字符串将作为链接显示在屏幕上,但它似乎忽略了锚标记,并且仅包括标记内的值。 例如某事变成了“某事”

private generateAnchors(content: string) {
    let contentToReturn = content;
    if (content.indexOf('@') < 0) return contentToReturn;
    else if (content.indexOf('@') > -1) {
        let tag = content.substring(content.indexOf('@'), content.indexOf(' ', content.indexOf('@')));
        let address = tag.substring(1, tag.length);
        let anchor = '<a href="/home/user/"'+address+'>'+tag+'</a>';
        console.log('found substr: '+tag, ' '+address+' '+anchor);
        contentToReturn.replace(tag, anchor);
        console.log('final string: '+contentToReturn);
    }
    return contentToReturn;
}

这是如何在 Angular/TypeScript 中完成的?

【问题讨论】:

标签: string angular typescript anchor


【解决方案1】:

您是否尝试替换:

contentToReturn.replace(tag, anchor);

与:

contentToReturn = contentToReturn.replace(tag, anchor);

String.replace 不会更改您的字符串,因为它是不可变的,它只是返回一个替换完成的新字符串。


Angular Templating

除了这个小问题,你应该考虑使用 Angular 的模板机制。您应该阅读文档以了解这一点,但我会尝试为您提供一个适合您的特定情况的示例。

您将拥有一个包含以下内容的 links.component.html 文件:

<a href="/home/user/{{address}}">{{tag}}</a>

如果您需要其中几个,也可以是一个循环:

<div *ngFor="let link in links">
  <a href="/home/user/{{link.address}}">{{link.tag}}</a>
</div>

还有一个对应的links.component.ts和对应的元素:

import { Component } from "@angular/core";

@Component({
  selector?: "app-links-component"
  templateUrl: "links.component.html"
})
export class LinksComponent {
  address: string;
  tag: string;

  constructor() {}

  // ts logic to fill address/tag information
}

或者第二种情况的数组:

import { Component } from "@angular/core";

@Component({
  selector?: "app-links-component"
  templateUrl: "links.component.html"
})
export class LinksComponent {
  links: Link[] = [];

  constructor() {}

  generateAnchors(address: string, tag: string) {
    // You can bind this method to a form submit or something.
    this.links.push(new Link(address, tag));
  }
}

N.B.:既然都是用心写的,可能会有错别字……

【讨论】:

    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2017-03-18
    • 2020-04-02
    • 2016-04-24
    相关资源
    最近更新 更多