Search code examples
angularangular2-templateangular2-formsangular-ngmodeltwo-way-binding

Setting ngModel dynamically


I am trying to build a basic Polling App which has the fields as shown in the image. This is the view of the app. The template of the App. The ts file for the component. I haven't written any kinda logic in this file just logging out the value of the form. As I enter value for the first field the second field also gets updated with the same value.  How can I achieve two way binding in this case?

Since there are fields for two inputs i want binding for each field(Option 1 & Option 2 as option1 and option2 respectively so i can reference it in the ts file.) But when I type option for the first field the second field also gets the same value & likewise for the second field. How can I set two way binding for each of the input field?

After I click on Create Poll button the console displays as: { "question": "Who will win World Cup?", "option1": "Germany", "option2": "Germany" }


Solution

  • Use your index:

    [(ngModel)]="options[i]"
    

    and create an option array in the component