Reputation: 1233
My app allows the user to select from a dropdown of events, each of which has its own unique set of properties and property values that can be selected.
This is represented as a FormGroup for the event, with a FormControl for each property of the event. 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. I am doing this in order to be able to reset the event property select dropdowns and set their default values when the event is changed.
For example event 1 has properties "prop1" and "prop2" and event 2 has properties "prop3", "prop4", and "prop5". When the page is loaded event 1 is selected and two select dropdowns are displayed, one for prop1 and one for prop2, each with their own set of values. When the user selects event 2 the existing select dropdowns are removed and in their place are three new ones for prop3, prop4, and prop5.
Refreshing the event property dropdowns is working without using FormBuilder, FormGroup, and FormControl. The issue is that when multiple events have a property with the same name the property dropdowns get out of sync with the underlying data (which is reset upon event selection), and the property dropdowns maintain old user-selected values instead of being reset.
When I try to use FormBuilder, etc this error is thrown:
Error: No value accessor for form control with name: '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>
The answers that I've found so far use static formControlName values in the template, which won't work here. My dynamic formControlName template references do seem to work as the error message includes the correct property name ("prop1"). I'm trying to avoid using ngModel as the data model and form model do vary. How can I fix this?
Upvotes: 0
Views: 1731
Reputation: 24864
You have to put [formControlName]
in <select>
:
<select [formControlName]="myCtrl"...>
Upvotes: 0