I have a bunch of input fields in a *ngFor
loop. The documentation says that template reference variables should be unique. Is there a way to do something like
If you have an iterable series of Inputs in your form and a decent amount of logic regarding how you want the form to respond to user input the ReactiveFormsModule
is going to be a much better fit. This way you don't have to worry about template reference variables and can interact with the FormControls directly.
Essentially with Reactive Forms it would look something like
Component
// Initialize your Form
initForm(): void {
this.Form = this._FormBuilder.group({
arrayOfInputs: this._FormBuilder.array(initArray())
})
}
// Initialize the Array of Inputs
initArray(): FormGroup[] {
return [
{ this._FormBuilder.group({ inputValue: [''] }),
{ this._FormBuilder.group({ inputValue: [''] }),
{ this._FormBuilder.group({ inputValue: [''] })
]
}
Template
There's a few things missing here, but generally this is how I build forms that have interable inputs. The major difference is that usually when initializing the FormArray, I am using data pulled from somewhere. It really helps to build your forms in logical chunks.
Reactive Forms