& lt; textarea& gt;当将formControlName添加到& lt; textarea& gt;时,默认内容消失元素 [英] <textarea> default content disappears when adding formControlName the <textarea> element

查看:128
本文介绍了& lt; textarea& gt;当将formControlName添加到& lt; textarea& gt;时,默认内容消失元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 4.0.2中创建一个反应形式,该形式具有一个< textarea> 字段,该字段具有默认内容,并从数据库中提取.显示< textarea> 中的内容没有任何问题,但是当我将 formControlName ="sectionContent" 添加到< textarea> 中时>元素,其中的内容就会消失.

I'm trying to create a Reactive Form in Angular 4.0.2, which has a <textarea> field with default content, pulled from the database. The content in the <textarea> is showing without any issues, but when I add the formControlName="sectionContent" to the <textarea> element, the content from it disappears.

< textarea formControlName ="sectionContent"> {{section.sectionContent}}</textarea >

此问题仅在< textarea> 元素中发生,因为我在表单中还有其他< input> 字段,但这些内容仍然出现.

This issue is only happening with the <textarea> element, as I have other <input> fields in the form, but those contents are still appearing.

FormGroup看起来像这样:

The FormGroup looks like this:

this.sectionForm = new FormGroup({
  sectionTitle: new FormControl(),
  sectionContent : new FormControl()
});

有人遇到过这个问题吗?

Did anyone encountered this issue?

推荐答案

改用默认值

this.sectionForm = new FormGroup({
  sectionTitle: new FormControl(),
  sectionContent : new FormControl(this.section.sectionContent)
});

模板

<textarea formControlName="sectionContent"></textarea>

或使用setValue/pathValue:

or using setValue/pathValue:

this.sectionForm = new FormGroup({
  sectionTitle: new FormControl(),
  sectionContent : new FormControl()
});
// after received data
this.sectionForm.patchValue({sectionContent: this.section.sectionContent});

演示: https://plnkr.co/edit/NWgzGdUc9cDkKujPgrl4?p=preview

文档:

https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html

setValue:

设置FormGroup的值.它接受与组的结构,以控件名称作为键.

Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.

此方法执行严格的检查,因此,如果您尝试设置一个不存在或排除的控件的值控件的值.

This method performs strict checks, so it will throw an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control.

patchValue:

patchValue:

修补FormGroup的值.它接受带有控制的对象名称作为键,并会尽最大努力将值与正确的值进行匹配组中的控件.

Patches the value of the FormGroup. It accepts an object with control names as keys, and will do its best to match the values to the correct controls in the group.

它接受该组的超集和子集,而不会抛出错误.

It accepts both super-sets and sub-sets of the group without throwing an error.

这篇关于&amp; lt; textarea&amp; gt;当将formControlName添加到&amp; lt; textarea&amp; gt;时,默认内容消失元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆