javascript - <textarea> 默认内容在 <textarea> 元素中添加 formControlName 时消失

标签 javascript angular angular2-forms angular-reactive-forms

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

相关文章:

java - 使用外部 JS 文件更改 Servlet 的 HTML 输出

javascript - 你如何让axios GET请求等待?

angular - Jhipster 4 如何在主屏幕上放置实体组件(列表)

angular - ngAfterContentChecked() 不可理解 + Angular 2

angular - 如何向嵌套表单组添加新的表单控件?

javascript - 如何在对象[object HTMLCollection]上插入Mysql数据文本

javascript - 将带有数组的数组映射到数组中

angular - 如何将 @Input() 参数传递给使用 DynamicComponentLoader 创建的 Angular 2 组件

页面加载时 Angular valuechanges 调用多次

angular - 带或不带括号的 formControlName?