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

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

String replace to html tag in Angular 13

问题

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

我有以下代码:

  1. export class KoniecComponent implements OnInit {
  2. // ...
  3. wiadomosc: string;
  4. urlView: string;
  5. constructor(
  6. private cService: CService
  7. ) { }
  8. ngOnInit(): void {
  9. this.registerC();
  10. }
  11. registerC(): void {
  12. this.cService.saveC(this.szkoda).subscribe(
  13. wynik => {
  14. const json = JSON.stringify(wynik);
  15. let txt = JSON.parse(json);
  16. if(txt.result_info != "" && txt.result_info != null)
  17. {
  18. let msg = txt.result_info;
  19. let url = txt.pm;
  20. this.urlView = txt.pm;
  21. this.wiadomosc = msg.replace(txt.number, '<b>'+txt.number+'</b>');
  22. }
  23. else {
  24. ...............
  25. }
  26. },
  27. error => {
  28. .......
  29. }
  30. );
  31. }
  32. }

我在这一行遇到了问题:

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

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

如何修复它?请帮助我。

英文:

I am beginner Angular developer.

i have this code:

  1. export class KoniecComponent implements OnInit {
  2. ....
  3. wiadomosc: string;
  4. urlView: string;
  5. constructor(
  6. private cService: CService
  7. ) { }
  8. ngOnInit(): void {
  9. this.registerC();
  10. }
  11. registerC(): void {
  12. this.cService.saveC(this.szkoda).subscribe(
  13. wynik =&gt; {
  14. const json = JSON.stringify(wynik);
  15. let txt = JSON.parse(json);
  16. if(txt.result_info != &quot;&quot; &amp;&amp; txt.result_info != null)
  17. {
  18. let msg = txt.result_info;
  19. let url = txt.pm;
  20. this.urlView = txt.pm;
  21. this.wiadomosc = msg.replace(txt.number, &#39;&lt;b&gt;&#39;+txt.number+&#39;&lt;/b&gt;&#39;);
  22. }
  23. else {
  24. ...............
  25. }
  26. },
  27. error =&gt; {
  28. .......
  29. }
  30. );
  31. }
  32. }

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:

确定