【问题标题】:Replace dynamically inserted keywords with user data angular 5用用户数据角度 5 替换动态插入的关键字
【发布时间】:2018-03-23 22:47:45
【问题描述】:

我不确定该叫什么,所以我在寻找答案时可能错过了一些东西,但基本上我有来自外部 api 的数据,它被插入到 innerHTML 标记中现在在返回的数据中是一些 html,然后由于innerHTML 而得到处理,但我在返回的 html 中有某些关键字,例如[username],我想用我存储的数据替换它。所以在我的 .ts 文件中我可能有..

username: 'name';

然后在我的html中我有

<div class='inner-html' [innerHTML]="data.html"></div>

在我来自data.html 的回复中,html 是这样的

<h1>Hey [userName] lorem ipsum...</h1>

所以我想用存储在username中的用户名替换从外部api动态传入的[userName]

我尝试将{{username}} 放入传入的 html 中.. 但这没有用,我也尝试了${username} 但也没有用..

我想知道是否还有其他方法?

编辑 我试过使用 str.replace();在 onChanges 生命周期事件中,但这不起作用我的代码是..

  const html = <HTMLElement>document.querySelector('.inner-html');
  html.innerHTML.replace('[userName]', this.username);

现在这样的事情一定是可能的,任何帮助将不胜感激

谢谢

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

Angular 正是为此目的提供了管道:

管道

Angular 管道是将输入值转换为输出的函数 在视图中显示的值。

它们提供可重用可扩展方式来实现您的目标。请检查一下,因为我认为这是您所追求的:

Live Solution

基本上,您通过转换管道输出[innerHTML]

<div class='inner-html' [innerHTML]="data.html | parseInnerHtml:replacements"></div>

parseInnerHtml 是自定义管道,它需要替换键的哈希值和相应的值来替换:

import { Input, Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'parseInnerHtml'})
export class ParseInnerHtml implements PipeTransform {
  transform(text: string, replacements: Object): string {
    let search = Object.keys(replacements);
    for(let i = 0; i < search.length; i++){
      text = text.replace('['+ search[i] +']', replacements[search[i]]);
    }
    return text;
  }
}

【讨论】:

  • 您应该修改您的替换方法,以便在要替换的字符串不止一次时它可以工作
  • 好建议,但如果需要,我会允许 OP 这样做。我已按要求回答了问题。
  • @Randy Casburn 嘿,这只是一个简单的问题.. 这很有效,但是.. 我在控制台中收到一个错误,上面写着cannot convert undefined or null to object on line 5 of the parseInnerHtml pipe 我假设这是因为在此之前数据还没有进入打电话..有没有办法避免这种情况??
  • 听起来您没有创建具有替换的对象。这显示在 app.component.ts @ 第 9 行的解决方案中。您创建了吗?
【解决方案2】:

看起来您可以控制动态数据。如果是这样,如果您可以将服务器上的 html 转换为包含username,那将更有意义。

但是,如果您无法控制,您可以轻松地将 [username] 替换为您所拥有的。例如:

str.replace('[username]', this.username);

【讨论】:

  • 问题是如何使用 Angular 5 来实现这一点。
【解决方案3】:
-- in hello.component.ts
@Component({
  selector: 'hello',
  template: ``,
})
export class HelloComponent  {
  @Input() username: string;

  private _html: string;
  @HostBinding('innerHTML')
  @Input() set html(html: string) {
    this._html = html.replace('[userName]', this.username);
  }

  get html() {
     return this._html;
  }
}

-- in app.component.html
<hello [html]="html" [username]="username"></hello>

-- in app.component.ts
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  username = 'App user';
  html = '<h1>Hello [userName]!</h1>';
}

Live example

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多