1

I've worked out that I can create dynamic ngModel variables using this method. This works great because I'm trying to generate a bunch of text inputs based on a list and then put an ngModel variable on them. The problem I'm running into is I want to assign an initial value to the textbox so it displays this value (as well as being the value for the ngModel) and then obviously the user can type in the box, changing the value of the ngModel variable.

I can't work out a way to do this though. If I set a value for the input it's simply cleared. It also needs to be done with ngModel rather than 2 way data binding (the {{}} method) because I need to be able to reference the variable later.

Below is my attempt to get it to work. You can assume "items" is a list of string values.

<ul>
 <li *ngFor = "let item of items">
  <input type = "text" [(ngModel)] = "input[item]" value = '{{item}}'>
 </li>
</ul> 

I'm also very new to Angular and web dev in general so I could just be missing something very obvious and if that's the case I apologise. Regardless I'd really appreciate any help.

jontycg
  • 277
  • 2
  • 16

1 Answers1

1

You should do this in your controller.

@Component({
    // component configuration
})
class MyController implements OnInit {

    public input: Object = {
        // your data
    };

    public items: Array<Object> = [
        // your list of items
    ];

    ngOnInit() {

        this.items.forEach(item => {
            input[item] = item;
        });

    }

}
Vladimir Zdenek
  • 2,240
  • 1
  • 17
  • 23
  • Cheers for that, it makes sense and I did think about doing it in a similar way, I was just curious if it was possible from the template. This should work as a good solution though so thanks! – jontycg Jun 12 '17 at 12:25
  • 1
    With Angular 2+, they are trying to "force" developers to move logic from template to controller, hence, I guess, the removal of ``ngInit`` directive. – Vladimir Zdenek Jun 12 '17 at 12:26
  • Oh that's interesting I wasn't aware that was the direction they were intending for. Thanks again for your help mate! – jontycg Jun 12 '17 at 12:28