How to set unique template reference variables inside an *ngFor? (Angular)

后端 未结 3 1011
小鲜肉
小鲜肉 2020-12-05 14:25

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

3条回答
  •  抹茶落季
    2020-12-05 14:48

    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

提交回复
热议问题