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

I have a set of input fields in an ngFor loop. The documentation says that reference template variables must be unique. Is there a way to make something like #attendee-{{person.id}}to make it unique?

   <div *ngFor="let person of attendeesList">
       <input #attendee [ngModel]="person.name" (blur)="changeName(attendee.value)"/>
   </div>

(I know that there is an opportunity to do it (ngModelChange)="changeName($event)", but there are reasons why I need to use blur. In particular, I do not want the model to change until a person types a name, and we confirmed that the name is not empty, not a duplicate name.

+4
source share
3 answers

Your reference template variable is already unique because you use it inside the built-in viewport:

<div *ngFor="let person of attendeesList">
  <input #attendee [ngModel]="person.name" (blur)="person.name = attendee.value"/>
</div>

Working example

, :

<div *ngFor="let person of attendeesList">
  <input [ngModel]="person.name" (blur)="person.name = $event.target.value"/>
</div>
+2

, ( ). ViewChildren.

@ViewChildren('attendee') attendeeInputs: QueryList<ElementRef>;

attendeeInputs QueryList .

+2

, , , ReactiveFormsModule . , FormControls.

// 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: [''] })
    ]
}

<ng-container formArrayName="formArray">
    <div [formGroupName]="i" *ngFor="let Inputs of Form.get('arrayOfInputs').controls; let i=index">
        <input formControlName="inputValue" type="text">
    </div>
</ng-container>

- , , , , . , FormArray , -. .

+2

Source: https://habr.com/ru/post/1692433/


All Articles