<textarea> default content disappears when adding formControlName the <textarea> element

こ雲淡風輕ζ 提交于 2019-12-23 12:28:18

问题


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>

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

The FormGroup looks like this:

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

Did anyone encountered this issue?


回答1:


using default value instead

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

template

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

or using setValue/pathValue:

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

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

Document:

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:

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:

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.



来源:https://stackoverflow.com/questions/43698965/textarea-default-content-disappears-when-adding-formcontrolname-the-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!