Angular ChangeDetection не отображает правильные данные - PullRequest
0 голосов
/ 27 ноября 2018

Я столкнулся с ситуацией, которую не могу решить.В моем проекте используется угловая 6. У меня есть форма, отображаемая в виде таблицы с использованием ngFor, и я сделал возможным добавлять строки в таблицу.

<table class="table">
    <thead>
        <tr>
            <th>Prestations</th>
            <th>Unité</th>
            <th>Prix</th>
            <th>Pourcentage Promotionnel</th>
            <th>Activez la promotion?</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let prestation of listPrestations">
            <td class="centering">
                <strong>
                    {{ prestation.prestation.label }}
                </strong>
            </td>
            <td class="centering">
                <strong>
                    {{ prestation.prestation.unite || 'Non défini' }}
                </strong>
            </td>
            <td>
                <div class="input-group" required>
                    <input type="number" step=0.1 [(ngModel)]="prestation.pricePerUnit" id="prestation-pricePerUnit-{{prestation.prestation.id}}" name="pricePerUnit" class="input-field righting" min=0 placeholder="Prix unitaire" required>
                    <label class="input-label" for="pricePerUnit">Prix unitaire</label>
                </div>
            </td>
            <td>
                <div class="input-group">
                    <input type="number" step=1 [(ngModel)]="prestation.promoPercentage" id="prestation-promoPercentage-{{prestation.prestation.id}}" name="promoPercentage" min=0 max=99 class="input-field righting" placeholder="Pourcentage Promotionnel">
                    <label class="input-label" for="promoPercentage">Pourcentage Promotion</label>
                </div>
            </td>
            <td class="centering">
                <input type="checkbox" [(ngModel)]="prestation.promoActivated" id="prestation-promoActivated-{{prestation.prestation.id}}" name="promoActivated" class="" placeholder="">
            </td>
            <td class="centering">
                <button class="btn btn-danger" (click)="deletePrestation(prestation.prestation.id)"><i class="fa fa-trash"></i></button>
            </td>
        </tr>
    </tbody>
</table>

, что дает что-то подобное Picture before click on Ambulance

но когда я добавляю строку в свой массив

add(prestationId: number) {
    var x: ICompanyPrestation[] = [];
    this.tmpPrestation = new CompanyPrestation();
    this.tmpPrestation.company = JSON.parse(JSON.stringify(this.company));
    this.tmpPrestation.prestation = this.prestations.find(prestation => prestation.id == prestationId);
    if (!this.listPrestations.find(prestation => prestation.prestation.id == prestationId)) {
        this.listPrestations.push(this.tmpPrestation);
    } else {
        this.isAlreadyIn();
    }
}

, я вижу, что массив содержит правильные данные, но кажется, что исходные входные данные отображаются как 0 "pricePerUnits" в массиве или«Прикс» на экране

.console.log of array after click on

Это как changeDetection не работает.

Screen after click on

Кто-нибудь знает, что не так в том, что я делаю ?!

Спасибо

Ответы [ 3 ]

0 голосов
/ 27 ноября 2018

Вы можете вручную запустить обнаружение изменений, вызвав detectChages

add(prestationId: number) {
    var x: ICompanyPrestation[] = [];
    this.tmpPrestation = new CompanyPrestation();
    this.tmpPrestation.company = JSON.parse(JSON.stringify(this.company));
    this.tmpPrestation.prestation = this.prestations.find(prestation => prestation.id == prestationId);
    if (!this.listPrestations.find(prestation => prestation.prestation.id == prestationId)) {
        this.listPrestations.push(this.tmpPrestation);
    } else {
        this.isAlreadyIn();
    }


    this.changeDetector.detectChanges();

}

Также добавьте его в конструктор

constructor(
    private changeDetector: ChangeDetectorRef,
) {
0 голосов
/ 27 ноября 2018

Я наконец узнал!

Кажется, в моем соглашении об именах произошла ошибка, связанная с "id", "name" и т. Д., И этого было достаточно для создания ошибки.

Спасибо

0 голосов
/ 27 ноября 2018

Angular не использует правильное отслеживание для получения данных.

Добавить пользовательскую функцию отслеживания.

<tr *ngFor="let prestation of listPrestations; trackBy: customTB">
customTB(item, index) {
  return `${index}-${item.id}`;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...