简体   繁体   English

带HTML字符串的角反应形式设置值

[英]Angular reactive form setting value with HTML string

I am trying to set a string value to the control with patchValue method. 我正在尝试使用patchValue方法将字符串值设置为控件。 The string value contains HTML tags but the HTML tags are translated as plain text for some reason. 字符串值包含HTML标记,但是出于某些原因,HTML标记被转换为纯文本。

<textarea rows="5" name="myField" formControlName="myField" readonly></textarea>

const htmlStr = '<p>HTML Content HERE</p>'
// assuming the form group instance already created
this.form.get('myField').patchValue(this.htmlStr);

The Angular API doc didn't say too much about how patchValue can handle the HTML value and is pretty generic though. Angular API文档并没有过多地提及patchValue如何处理HTML值,尽管它非常通用。

Adding Html String to a textArea will always show up as plain Html in the textarea. 向文本区域添加HTML字符串将始终在文本区域中显示为纯HTML。

The [innerHTML] can only be applied to span/div or paragraph elements. [innerHTML]仅可应用于span / div或段落元素。 You can not expect a html tag to show up as or (as it appears in HTML page mark up), if used inside a input field. 如果在输入字段中使用html标记,则不能期望html标记显示为或(显示在HTML页面标记中)。 it will always appear raw. 它将始终显示为原始。

Having said that, You can always patch a HTML string to your textarea but do not expect it to display as HTML mark up with all the styles etc. 话虽这么说,您始终可以将HTML字符串打补丁到您的文本区域,但不要期望它以HTML标记的所有样式显示。

You can check this stackBlitz here for example 您可以在此处检查此stackBlitz

It's probably because you are passing a type string and not a DOM element . 可能是因为您传递的是类型字符串,而不是DOM元素

Example: 例:

var domElementP         = document.createElement("p");
domElementP.textContent = 'TEXT HERE';
this.form.get('myField').patchValue(this.domElementP);

Libraries like jQuery allow easier creation of DOM elements. jQuery库允许更轻松地创建DOM元素。
For example: 例如:

// we assume that jQuery was loaded
var stringDOM = '<p>' +
  '<span>HTML Content HERE <i class="icon"></i></span>' +
'</p>';
var $jQueryObject            = $.parseHTML(stringDOM);
var domElement               = $jQueryObject[0];
this.form.get('myField').patchValue(this.domElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM