我在这种情况下遇到问题:
@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
}
})
}))
}
问题是ngModel无法正常工作,我看不到b属性更改。如果删除地图管道,并将boolean属性放在第一个数组中,则一切正常。我想念什么吗?有什么问题吗?
谢谢
{{item.b}}
中渲染了ngFor
,您将看到该值在true
和false
之间正确更改。如另一个答案中所述,这是由于引用和更改检测所致。您也可以使用ngOnInit
和subscribe
简单地将可观察数据保存为类的一个属性: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。为了避免内存泄漏,请不要忘记清理所有可观察到的东西。
<input type=checkbox (change)="change(item)" [(ngModel)]="item.b"/>
change(item) {
console.log(item);
}
这没有反映在dom上,因为items数组被映射到相同的内存位置,并且更改其中的元素不会引起角度变化检测以触发显示更改。
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);
}