我正在尝试在 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.
关于javascript - <textarea> 默认内容在 <textarea> 元素中添加 formControlName 时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698965/