<textarea> 添加 formControlName 到 <textarea> 元素时默认内容消失

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

我正在尝试在 Angular 4.0.2 中创建一个响应式表单,它有一个 <textarea> 字段,其中包含从数据库中提取的默认内容。 <textarea> 中的内容显示没有任何问题,但是当我将 formControlName="sectionContent" 添加到 <textarea> 元素时,它的内容消失了。

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

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

FormGroup 如下所示:

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

有人遇到过这个问题吗?

改用默认值

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

模板

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

或使用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

设置值:

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.

补丁值:

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.