Добавляем динамическую строку в таблицу, но она очищает данные в строке - PullRequest
0 голосов
/ 06 июня 2018

Что я тут не так делаю.Нужна помощь.

Когда я нажимаю кнопку «Добавить», данные, выбранные в строках таблицы, становятся пустыми.Но когда я выбираю кнопку «Удалить», а затем нажимаю на кнопку «Добавить», она не очищается только один раз.Если я вижу консоль, я вижу там данные, но они не отображаются на экране.enter image description here enter image description here Вот мой код:

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;
    }
}

Ответы [ 3 ]

0 голосов
/ 06 июня 2018

Конечно, строка очищается, потому что вы ее очищаете:

this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""};

Таким образом, при нажатии кнопки добавления связанные значения переопределяются, а затем вы толкаете ее вмассив.Таким образом они очищаются:)

0 голосов
/ 22 января 2019

Хорошо, решите проблему: -

Основная проблема в атрибуте name="".name="" должно различаться в каждой строке. Мы можем решить это двумя способами:

1) Либо изменить имя атрибута name="" динамически, чтобы для каждой строки было свое имя, я сделал это, чтобы добавитьиндекс с ним как

<input [(ngModel)]="notification.notificationLevel" name="notificationThreshold{{i}}" required class="form-control" type="text" />

2) Или избегать name="" и т. д. Мы можем избежать [(ngModel)] По [value] и (input) и можем использовать как: -

 <input [value]="notification.notificationLevel" (input)="notification.notificationLevel=$event.target.value" required class="form-control" type="text"/>
0 голосов
/ 06 июня 2018

На самом деле все ваши notificationArray элементы - это один и тот же экземпляр newNotification.Делая это: this.newNotification = {thresholdId: "0", notificationLevel: "", message: ""}; вы фактически сбрасываете первую строку из-за этого.

Попробуйте вместо этого сохранить newNotification в переменной:

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;
    }
}

update:

Я не знаю, связано ли это, но у вас будет дубликат threshold id на ваш выбор.Используйте свой i, чтобы сделать его уникальным.То же самое касается ваших входных имен.Вы должны добавить [] после имени поля, иначе будет отправлена ​​только последняя строка.

Я добавил console.log вашего массива после нажатия.Можете ли вы сказать в комментарии, сбрасывается ли первый индекс в этот момент?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...