While working with simple array forms in Angular 4, I encountered an unusual problem with ngModel 😢.
Take a look at my code first.
My Approach
Defining my form FormGroup:
public invoiceForm: FormGroup;
Setting my testing Data and Form Model:
readonly local = [ 'Lorem ipsum dolor sit amet', 'et iusto odio dignissim qui blandit', 'Epsum factorial non deposit', 'Ma quande lingues coalesce' ]; public localModel = this.local;
Define form group in ngOnInit and simply add my locals row into the form group:
this.invoiceForm = this._fb.group({ itemRows: this._fb.array([this.initItemRows()]) }); for (let index in this.local) this.setAndReplaceNewERow(+index)
Initially, everything seems correct. See result as image
The Issue
When I change one of the text inputs, the main variable also changes.
Before Change :
FormGroup
{
"itemRows": [
{
"itemname": "Lorem ipsum dolor sit amet"
},
{
"itemname": "et iusto odio dignissim qui blandit"
},
{
"itemname": "Epsum factorial non deposit"
},
{
"itemname": "Ma quande lingues coalesce"
}
]
}
My Local Data
[
"Lorem ipsum dolor sit amet",
"et iusto odio dignissim qui blandit",
"Epsum factorial non deposit",
"Ma quande lingues coalesce"
]
My Form Model
[
"Lorem ipsum dolor sit amet",
"et iusto odio dignissim qui blandit",
"Epsum factorial non deposit",
"Ma quande lingues coalesce"
]
After change :
FormGroup
{
"itemRows": [
{
"itemname": "Lorem ipsum dolor sit amet"
},
{
"itemname": "et iusto odio dignissim qui blandit"
},
{
"itemname": "changed !!!!!!!!!!!"
},
{
"itemname": "Ma quande lingues coalesce"
}
]
}
My Local Data
[
"Lorem ipsum dolor sit amet",
"et iusto odio dignissim qui blandit",
"changed !!!!!!!!!!!",
"Ma quande lingues coalesce"
]
My Form Model
[
"Lorem ipsum dolor sit amet",
"et iusto odio dignissim qui blandit",
"changed !!!!!!!!!!!",
"Ma quande lingues coalesce"
]
DEMO
Please check out the Plunk Demo