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

Csaba picture Csaba · Apr 29, 2017 · Viewed 8.5k times · Source

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?

Answer

Tiep Phan picture Tiep Phan · Apr 29, 2017

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.