angular - 数组未在 DOM 中拼接,但在控制台中是 - Ionic 2+/Angular2+

标签 angular typescript ionic-framework ionic2

我有一个充满项目和值的动态数组。当用户单击项目上的按钮时,它应该从 View 列表中删除该项目。我完全猜不到这是为什么。数据的结构如何?我不这么认为,因为它表明它正在控制台中被删除。无论如何,谢谢!

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

最佳答案

尝试执行以下操作:

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

你也可以尝试在构造函数中注入(inject)public zone: NgZone然后运行 在 this.zone.run(() => { this.items.splice(i, 1); }); 中拼接。这是另一种强制更改检测的方法。

编辑:

在您的 getItems() 方法中,尝试这样做:

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

Plunker 引用:

Plunker demonstration

关于angular - 数组未在 DOM 中拼接,但在控制台中是 - Ionic 2+/Angular2+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764391/

相关文章:

angular - Angular 库与 monorepo 中的 Angular 模块的优势? NX架构

php - 否 'Access-Control-Allow-Origin' ionic PhpMyAdmin

angular - 如何获取对象数组值

angular - 我们如何在 Angular 7 中为绝对路径配置 Stylus?

angular - 如何对组件类应用单一职责?

javascript - 参数在 RN typescript 中隐式具有任何类型

javascript - TypeScript 编译器 api : get position in generated code of a specific AST node

css - Ionic 全高列表

arrays - 无法获取数组 Angular 中的第一项

angular - 如何在输入字段右侧对齐 Material 图标?