【问题标题】:Angular 4 FormBuilder, FormGroup with dynamic FormControlsAngular 4 FormBuilder,带有动态FormControls的FormGroup
【发布时间】:2017-11-12 18:24:21
【问题描述】:

我的应用允许用户从事件下拉列表中进行选择,每个事件都有自己独特的一组可供选择的属性和属性值。

这表示为事件的 FormGroup,事件的每个属性都有一个 FormControl。 On initialization the FormGroup is populated with the default event's properties, and when a new event is selected the FormGroup will have all old FormControls removed before populating it with the new event's properties' FormControls.我这样做是为了能够在事件更改时重置事件属性选择下拉菜单并设置它们的默认值。

例如,事件 1 具有属性“prop1”和“prop2”,事件 2 具有属性“prop3”、“prop4”和“prop5”。加载页面时,选择事件 1 并显示两个选择下拉列表,一个用于 prop1,一个用于 prop2,每个都有自己的一组值。当用户选择事件 2 时,现有的选择下拉菜单将被移除,取而代之的是 prop3、prop4 和 prop5 的三个新下拉菜单。

在不使用 FormBuilder、FormGroup 和 FormControl 的情况下刷新事件属性下拉列表。问题是,当多个事件具有同名的属性时,属性下拉列表与基础数据不同步(在事件选择时重置),并且属性下拉列表保持旧的用户选择值而不是被重置。

当我尝试使用 FormBuilder 等时,会抛出此错误:

错误:表单控件没有值访问器,名称为:'prop1'



app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...

@NgModule({
  ...
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    ReactiveFormsModule
  ],



app.component.ts

import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
...

@Component({
  ...
})
export class AppComponent implements OnInit {
  ...
  propertiesFormGroup: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.propertiesFormGroup = this.fb.group({});
    ...
    for (let p in this.propertiesDefinitions) {
      pValues = [...];
      this.propertiesFormGroup.addControl(p, new FormControl(pValues[0]));



app.component.html

<div id="property-container" [formGroup]="propertiesFormGroup">
  ...
  <ul id="event-properties">
    <li *ngFor="let p of properties">
      <select ...>
        <option *ngFor="let v of pValues" [formControlName]="p">{{ v }}</option>



到目前为止,我找到的答案在模板中使用静态 formControlName 值,这在这里不起作用。我的动态 formControlName 模板引用似乎确实有效,因为错误消息包含正确的属性名称(“prop1”)。我试图避免使用 ngModel,因为数据模型和表单模型确实有所不同。我该如何解决这个问题?

【问题讨论】:

  • 不应该[formControlName]进入&lt;select&gt;吗?
  • 请在 plunker 中重现该问题 :)
  • @developer033 解决了,谢谢。如果您想将其写为答案,我会接受。

标签: angular


【解决方案1】:

您必须将[formControlName] 放入&lt;select&gt;

<select [formControlName]="myCtrl"...>

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2022-01-23
    • 2021-02-20
    • 2018-01-27
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多