Что я делаю неправильно здесь. Нужна помощь.
Когда я нажимаю кнопку "Добавить", данные, которые я выбрал в строках таблицы, становятся пустыми. Но когда я выбираю кнопку "Удалить", а затем нажимаю кнопку "Добавить", то она не опорожняется только один раз. Если я вижу консоль, я вижу данные там, но она не появляется на экране. Вот мой код:
HTML:
<div class="container">
<div class="row" style="margin-bottom: 10px;">
<div class="col">
<div class="row111">
<label for="Select Image" class="col-sm-311 col-form-label111">Add Threshold and Notification for this Inspection: </label>
<div class="col-sm-9">
</div>
</div>
</div>
<div class="col">
<div class="float-right">
<button class="btn btn-default" type="button" (click)="addNotification()">Add</button>
</div>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>Threshold</th>
<th>Notification Level</th>
<th>Message</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- <tr> -->
<tr *ngFor="let notification of notificationArray; let i = index">
<td>{{i+1}}</td>
<td>
<select class="form-control" maxlength="50" readonly
required
id="threshold"
name="notification.thresholdId"
[(ngModel)]="notification.thresholdId"
#threshold="ngModel" >
<option value="0" selected> Select </option>
<option *ngFor="let threshold of thresholdList" value="{{threshold.thresholdId}}" >
{{threshold.threshold}}
</option>
</select>
</td>
<td>
<input [(ngModel)]="notification.notificationLevel" required class="form-control" type="text" name="notification.notificationLevel" />
</td>
<td>
<input [(ngModel)]="notification.message" required class="form-control" type="text" name="notification.message" />
</td>
<td>
<button class="btn btn-default" type="button" (click)="deleteNotification(i)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
component.ts:
notificationArray: Array<NotificationLevel> = [];
newNotification: any = {};
ngOnInit(): void {
this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
this.notificationArray.push(this.newNotification);
}
addNotification(index) {
this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
this.notificationArray.push(this.newNotification);
console.log(this.notificationArray); // I can see all entered data in console
return true;
}
deleteNotification(index) {
if(this.notificationArray.length ==1) {
alert("At least one Notification Required for an Inspection");
return false;
} else {
this.notificationArray.splice(index, 1);
return true;
}
}
Хорошо, решите проблему: -
Основная проблема в атрибуте name=""
. name=""
должно отличаться в каждой строке. Мы можем решить это двумя способами:
1) Либо измените name=""
атрибута name=""
динамически, чтобы для каждой строки оно имело свое имя, я сделал это, чтобы добавить индекс с ним как
<input [(ngModel)]="notification.notificationLevel" name="notificationThreshold{{i}}" required class="form-control" type="text" />
2) Или избегайте name=""
и поэтому мы можем избежать [(ngModel)]
By [value]
и (input)
и можем использовать как:
<input [value]="notification.notificationLevel" (input)="notification.notificationLevel=$event.target.value" required class="form-control" type="text"/>
Фактически, все ваши элементы notificationArray
являются тем же самым экземпляром newNotification
. Делая это: this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
вы действительно сбросили первую строку тоже из-за этого.
Попробуйте сохранить newNotification
в var вместо этого:
notificationArray: Array<NotificationLevel> = [];
newNotification: any = {};
ngOnInit(): void {
var newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
this.notificationArray.push(newNotification);
}
addNotification(index) {
console.log(this.notificationArray);
// here is the correction
var newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
this.notificationArray.push(newNotification);
console.log(this.notificationArray);
return true;
}
deleteNotification(index) {
if(this.notificationArray.length ==1) {
alert("At least one Notification Required for an Inspection");
return false;
} else {
this.notificationArray.splice(index, 1);
return true;
}
}
Обновить :
Я не знаю, связано ли это, но у вас будет threshold
идентификатор threshold
при выборе. Используйте свой i
чтобы сделать его уникальным. Это то же самое для ваших входных имен. Вы должны добавить []
после имени поля, иначе будет отправлена только последняя строка.
Я добавил console.log
из массива после нажатия. Можете ли вы сказать в комментарии, если первый индекс сбрасывается в этот момент?
Конечно, строка очищается, потому что вы очищаете ее:
this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};
Таким образом, нажав кнопку "Добавить", связанные значения переопределяются, а затем вы вставляете их в массив. Таким образом, они очищаются :)