3
votes

Take this basic input

<form (submit)="input_button($event)">
        <input
            type="text"
            [(ngModel)]="input_text"
            name="code"/>
            <br/>

    <input
        type="submit"
        value="Ok"/>
    </form>
    {{input_text}}

with a simple string input_text in your component. It's working, good. Ths two-way data binding is working and you can see the value of you input bellow your button.

Now, replace input_text in your component with

input_text:Array<string> = ['A', 'B', 'C', 'D'];

And in your template try this :

<form (submit)="input_button($event)">
        <input
            *ngFor="let text of input_text; let i = index"
            type="text"
            [(ngModel)]="input_text[i]"
            name="code_{{i}}"/>
            <br/>

    <input
        type="submit"
        value="Ok"/>
    </form>
    {{input_text}}

You have 4 inputs, well initialisez (with the correct name). But when you try to put text in a field, you lost the focus and the input_text array is unchanged ( {{input_text}} show always the same array )

Replacing [(ngModel)]="input_text[i]" with [(ngModel)]="text" does nothing

Can someone explain what is happening here ?

Thanks a lot !

2
I think that automatic change detection cannot occur for elements of an array. As such, initialization goes ok, but it can't simply automatically h later You can have a look at these questions for how to force change detection in these cases : stackoverflow.com/questions/35748484/… stackoverflow.com/questions/42962394/… - Pac0
I would suggest using Model Driven Forms, it will work a lot better for your scenario. but if you wanna using template driven then provide a plnkr - Nadhir Falta
Have a look at IterableDiffers - Pac0
Try adding trackBy in your ngFor directive, as suggested in this answer, and as illustrated in this plunker. - ConnorsFan
i already tryed trackBy. I'm not losing focus but the input_text array is still unchanged - dc-p8

2 Answers

0
votes

Try init in your component input_text: Array<object> = [{name: 'A'}, {name: 'B'}, {name: 'C'}, {name: 'D'}]; and run this code:

<form (submit)="input_button($event)">
    <input
        *ngFor="let text of input_text; let i = index"
        type="text"
        [(ngModel)]="input_text[i].name"
        name="code_{{i}}"/>
        <br/>

<input
    type="submit"
    value="Ok"/>
</form>
{{input_text | json}}
0
votes

Well, trackBy is working but {{input_text}} doesn't trigger because it's an object

Thanks all for help