如何使用响应式表单 Angular 的 html 标签显示内容

问题描述 投票:0回答:1

组件.html

<form [formGroup]="formName">
  <input formControlName="title">
</form>

组件.ts

this.formName.patchValue({
  title = this.content
})

有时

this.content
包含 html 标签,例如
<i>
/
<b>
标签。在这种情况下,标签也会显示。 我们如何才能以斜体或粗体显示该特定文本。 示例:
this.content = Solve ur doubts in (<i>StackOverflow</i>)
预期输出:解决您在 (StackOverflow)

中的疑问

一般来说,通过在 [innerHTML] 属性中传递 this.content 解决了这个问题。 但就我而言,它是一种反应式形式,无法使用innerHtML。 有人可以建议如何才能获得输出解决你在(StackOverflow)中的疑问

提前致谢。

angular angular-reactive-forms innerhtml html-tag-details
1个回答
0
投票

你可以使用innerHTML,例如:

<div [innerHTML]="content"></div>

小心,在你的 patchValues 中,它不是等号而是冒号

this.formName.patchValue({ title: this.content })

在某些情况下,您需要指定 html 是“安全的”。例如,如果它来自 API 我建议你做一个管道来简化

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(value: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

使用方法:

<div [innerHTML]="content | safeHtml"></div>
© www.soinside.com 2019 - 2024. All rights reserved.