ngFor内的角ngModel,带有管道和地图,不起作用

问题描述 投票:1回答:2

我在这种情况下遇到问题:

@Component({
  selector: 'my-app',
  template: `
    {{items | async| json}}

    <div *ngFor="let item of items | async">
      <input type=checkbox [(ngModel)]="item.b"/>
    </div>
  `
})
export class AppComponent  {
  items = of([{
    name: '1',
  },
  {
    name: '2',
  },
  {
    name: '3',
  }])
  .pipe(map(i=>{
    return i.map(i=>{
      return {
        i: i,
        b: false
      }
    })
  }))
}

Stackblitz app

问题是ngModel无法正常工作,我看不到b属性更改。如果删除地图管道,并将boolean属性放在第一个数组中,则一切正常。我想念什么吗?有什么问题吗?

谢谢

angular rxjs angular-ngmodel
2个回答
3
投票
您没有做错任何事情。如果在{{item.b}}中渲染了ngFor,您将看到该值在truefalse之间正确更改。如另一个答案中所述,这是由于引用和更改检测所致。您也可以使用ngOnInitsubscribe简单地将可观察数据保存为类的一个属性:

import { Component } from "@angular/core"; import { of } from "rxjs"; import { map } from "rxjs/operators"; @Component({ selector: "my-app", template: ` {{ items | json }} <form #myForm="ngForm"> <div *ngFor="let item of items"> <input [name]="item.i.name" type="checkbox" [(ngModel)]="item.b" /> </div> </form> ` }) export class AppComponent { items: any[] = []; ngOnInit() { this.getData().subscribe(data => (this.items = data)); } private getData() { return of([ { name: "1" }, { name: "2" }, { name: "3" } ]).pipe( map(i => { return i.map(i => { return { i: i, b: false }; }); }) ); } }

这里是一个正在运行的example。为了避免内存泄漏,请不要忘记清理所有可观察到的东西。

2
投票
实际上您在做什么是正确的。要检查我的意思,请将您的代码更改为此:

<input type=checkbox (change)="change(item)" [(ngModel)]="item.b"/> change(item) { console.log(item); }

这没有反映在dom上,因为items数组被映射到相同的内存位置,并且更改其中的元素不会引起角度变化检测以触发显示更改。

0
投票
您可以使用普通的javascript映射并简化流:

import { Component } from '@angular/core'; import { of }from 'rxjs' @Component({ selector: 'my-app', template: ` {{items | async | json}} <div *ngFor="let item of items | async"> <input type=checkbox [(ngModel)]="item.b"/> </div> ` }) export class AppComponent { private array = [ { name: '1' }, { name: '2'}, { name: '3' } ].map(i => ({i, b: false})); items = of(this.array); }

© www.soinside.com 2019 - 2024. All rights reserved.