Подтвердить что ты не робот

Массив не получает сращивание в DOM, а в консоли - Ionic 2 +/Angular2 +

У меня есть динамический array полный элементов и значений. Когда пользователь нажимает кнопку на элементе, он должен удалить элемент из списка. Я все догадываюсь, почему это так. Будут ли данные структурированы? Я бы не подумал, потому что это показывает, что он удаляется в консоли. В любом случае спасибо!

TS:

export class Page{
    items: Item[];

    constructor(public alertCtrl: AlertController){}

    removeitem(i) {
        let confirm = this.alertCtrl.create({
            title: 'Confirm',
            message: "text.",
            buttons: [
                {
                    text: 'Cancel',
                    handler: () => {
                        console.log('Disagree clicked');
                    }
                },
                {
                    text: 'Save',
                    handler: () => { 
                        this.presentToast() 
                        this.items.splice(i, 1);

                    }
                }
            ]
        });
        confirm.present();
    }

getItems(){
   this.stopService.getItems().subscribe(item => { 
     this.items = item 
  })

  }


}

HTML:

<div *ngFor="let item of items; index as i ">
    <h3>{{item.description}}</h3>
    <button item-end ion-button full (click)="removeitem(i)">remove item</button>
</div>

ИЗМЕНИТЬ

добавление сервиса, как я получаю элементы -

getItems(): Observable<any> {
         return this.http.get(someEndpoint)
        .map(res => res.json());
    }
4b9b3361

Ответ 1

Попробуйте сделать следующее:

removeitem(i) {
        let confirm = this.alertCtrl.create({
            title: 'Confirm',
            message: "text.",
            buttons: [
                {
                    text: 'Cancel',
                    handler: () => {
                        console.log('Disagree clicked');
                    }
                },
                {
                    text: 'Save',
                    handler: () => { 
                        this.presentToast() 
                        this.items = [...this.items.filter((item, index) => index !== i];
                    }
                }
            ]
        });
        confirm.present();
    }

Это полностью изменяет ссылку на объект и должно инициировать обновление DOM.

Если это не сработает, попробуйте обернуть сращивание в setTimeout:

setTimeout(() => { this.items.splice(i, 1); }, 0);

Вы также можете попробовать ввести public zone: NgZone в конструктор и запустить сращивание в this.zone.run(() => { this.items.splice(i, 1); });. Это еще один способ принудительного обнаружения изменений.

EDIT:

В вашем методе getItems() попробуйте сделать это:

    getItems() {
       this.stopService.getItems().subscribe(item => { 
         this.items = [...item];
      });
   }

Ссылка на плункер:

демонстрация плунжера

Ответ 3

Как сказал @robbannn, angular не обнаруживает изменения, поэтому измените

this.items.splice(i, 1);

Для

this.item = this.items.splice(i, 1).slice()

Ответ 4

Похоже, что детектор изменений Angular не срабатывал. Вы можете его вручную вызвать:

import {  ChangeDetectorRef } from '@angular/core';
constructor(private changeDetectorRef: ChangeDetectorRef  ){

}
removeitem(i) {
        let confirm = this.alertCtrl.create({
            title: 'Confirm',
            message: "text.",
            buttons: [
                {
                    text: 'Cancel',
                    handler: () => {
                        console.log('Disagree clicked');
                    }
                },
                {
                    text: 'Save',
                    handler: () => { 
                        this.presentToast() 
                        this.items.splice(i, 1);
                        this.changeDetectorRef.detectChanges();//call ng2 change detector here
                    }
                }
            ]
        });
        confirm.present();
    }