将字符串替换为HTML标签在Angular 13中

huangapple go评论102阅读模式
英文:

String replace to html tag in Angular 13

问题

我是一个初级的Angular开发者。

我有以下代码:

export class KoniecComponent implements OnInit {

  // ...
  wiadomosc: string;
  urlView: string;

  constructor(
    private cService: CService
  ) { }

  ngOnInit(): void {
    this.registerC();
  }

  registerC(): void {
    this.cService.saveC(this.szkoda).subscribe(
      wynik => {
       
        const json = JSON.stringify(wynik);
        let txt = JSON.parse(json);

        if(txt.result_info != "" && txt.result_info != null)
        {
          let msg = txt.result_info;
          let url = txt.pm;
          this.urlView = txt.pm;
          this.wiadomosc = msg.replace(txt.number, '<b>'+txt.number+'</b>');
        }
        else {
          ...............
        }
      },
      error => {
        .......
      }
    );
  }

}

我在这一行遇到了问题:

this.wiadomosc = msg.replace(txt.number, '<b>'+txt.number+'</b>');

结果中我得到了 <b> 标签 - 文本没有加粗。

如何修复它?请帮助我。

英文:

I am beginner Angular developer.

i have this code:

export class KoniecComponent implements OnInit {

  ....
  wiadomosc: string;
  urlView: string;

  constructor(
    private cService: CService
  ) { }

  ngOnInit(): void {
    this.registerC();
  }

  registerC(): void {
    this.cService.saveC(this.szkoda).subscribe(
      wynik =&gt; {
       
        const json = JSON.stringify(wynik);
        let txt = JSON.parse(json);

        if(txt.result_info != &quot;&quot; &amp;&amp; txt.result_info != null)
        {
          let msg = txt.result_info;
          let url = txt.pm;
          this.urlView = txt.pm;
          this.wiadomosc = msg.replace(txt.number, &#39;&lt;b&gt;&#39;+txt.number+&#39;&lt;/b&gt;&#39;);
        }
        else {
          ...............
        }
      },
      error =&gt; {
        .......
      }
    );
  }

}

I have problem with this line:

this.wiadomosc = msg.replace(txt.number, '<b>'+txt.number+'</b>');

In result i have 'b' tabs - not bolded text.

How can i repeir it? Please help me

答案1

得分: 0

在这里你可以像这样使用。
this.wiadomosc = msg.replace(txt.number, '&#39;&lt;b&gt;{{txt.number}}&lt;/b&gt;&#39;);

英文:

Here you can use like this.
this.wiadomosc = msg.replace(txt.number, &#39;&lt;b&gt;{{txt.number}}&lt;/b&gt;&#39;);

答案2

得分: 0

如果你想在Angular中加载富HTML文本,那么插值将不起作用,你需要将其设置在innerHTML属性内,像这样。
<span [innerHTML]="wiadomosc"></span> 这将加载 <b>test</b> test 作为DOM中的粗体。

英文:

If you want to load rich html text in angular then interpolation will not work
you need to set it inside innerHTML attribute like this.
&lt;span [innerHTML]=&quot;wiadomosc&quot;&gt;&lt;/span&gt; this will load &lt;b&gt;test&lt;/b&gt; test as bold in DOM

huangapple
  • 本文由 发表于 2023年6月15日 23:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定