Angular 2 material missing values from inputs in *ngFor
<div *ngFor="let item of products.product.parameters">
<div class="row">
<div class="input-field col s6">
<input id="param_name" class="autocomplete" required min="1" type="text" name="name" [(ngModel)]="item.name">
<label for="param_name">Name</label>
</div>
<div class="input-field col s6">
<input id="param_value" required min="1" type="text" name="value" [(ngModel)]="item.value">
<label for="param_value">Value</label>
</div>
</div>
</div>
Above is a piece of HTML that displays all the parameters, as well as a button for adding a new parameter, it is added to the array products.product.parameters
.
Everything seems to be fine, the old values from the array do not disappear, new ones are added, a new bar with 2 <input>
appears on the form, but(!) the values contained in all the previous <input>
stop being displayed, i.e. they just look like empty, although the data from the array does not disappear anywhere.
Tried below via <span>
output data - everything is ok, it disappears from <input>
.
How to deal with this?
1
Author: Никита Крагель, 2017-02-12
2 answers
You need to give each element a unique name
<div *ngFor="let item of products.product.parameters; let i = index">
<div class="row">
<div class="input-field col s6">
<input id="param_name" class="autocomplete" required min="1"
type="text" name="name-{{i}}" [(ngModel)]="item.name">
<label for="param_name">Name</label>
</div>
<div class="input-field col s6">
<input id="param_value" required min="1" type="text" name="value-{{i}}" [(ngModel)]="item.value">
<label for="param_value">Value</label>
</div>
</div>
0
Author: Eugene Tyan, 2017-11-22 01:22:25
I attached the working code in a slightly different style.
P.S. If something is not clear-ask.
angular.module('some', [])
.controller('someCtrl', function($scope) {
$scope.products = {
product: {
parameters: [
{ name: 'its name', value: 'its value' },
{ name: 'its name 2', value: 'its value 2' }
]
}
};
$scope.addRow = function() {
$scope.products.product.parameters.push({});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="some" ng-controller="someCtrl">
<div ng-repeat="item in products.product.parameters">
<div class="row">
<div class="input-field col s6">
<input id="param_name" class="autocomplete" required min="1" type="text" name="name" ng-model="item.name">
<label for="param_name">Name {{$index}}</label>
</div>
<div class="input-field col s6">
<input id="param_value" required min="1" type="text" name="value" ng-model="item.value">
<label for="param_value">Value {{$index}}</label>
</div>
</div>
</div>
<button ng-click="addRow()">Добавить строку</button>
<br />
<pre>{{products.product.parameters}}</pre>
</div>
0
Author: mix, 2017-02-12 11:03:47