0

I there a way to create the "ngModel" parameter in template driven forms as a dynamic name (for ex. by loop)?

I wish to get something like:

<div *ngFor='let d of items; let i = index;'>
    <input type="text" name="street" 
    [(ngModel)]="d.surname" #surname{{d.myindex}}="ngModel">
</div>

where the "d.myindex" is the dynamic name.

Nat
  • 43
  • 1
  • 4
  • You shouldn't need to do that. You should use `#surname="ngModel"`. – ConnorsFan Mar 13 '19 at 16:57
  • but I am creating several input fields by the array length. I can't call them all the same name. – Nat Mar 13 '19 at 16:59
  • Please show us how you want to use the `#surname` template reference variable. – ConnorsFan Mar 13 '19 at 17:00
  • Thats the example I wrote. I have the items array, and I wish to create input fields based on this array. – Nat Mar 13 '19 at 17:01
  • The example shows that you want to define the `#surname` variable, but not what you want to do with it. Do you need it? – ConnorsFan Mar 13 '19 at 17:02
  • I need it this way so I could use another field for: surname{{d.myindex}}.control.markAsTouched() – Nat Mar 13 '19 at 17:03
  • Please add the code and the context where you want to do that. It can probably be done with the same template variable name for all the input fileds. By the way, you cannot define these variables with dynamic names. – ConnorsFan Mar 13 '19 at 17:05

1 Answers1

0

I don't know what is your requirement to make it dynamic but... TemplateRef is not for that.

TemplateRef => it is block scoped though it has the same name while looping. You can use the ViewChildren decorator which returns all items of an ItemType and the remaining magic Angular does it for you.

component.ts

<div *ngFor="let i of [0, 1, 2, 3]" #items>
     <button (click)="onClick(items, i)">Click on item {{ i }}</button>
</div> 

.html

@ViewChildren('items') items: ItemType<ElementRef>;

 onClick(item, i) {
    console.log('item clicked : ', item);
    console.log('index of item : ', i);
    console.log('all items : ', this.items)
 } 

I'm not clear, what do you want but I just showed a way with click event please apply it for your input

for more details please check: https://stackoverflow.com/a/44441164/5835354

skdonthi
  • 1,308
  • 1
  • 18
  • 31