ngFor
を使用して作成されたリストの周りにngIf
コンテナをラップすると、Angular2で予期しない動作が発生します。 ngIf
コンテナが表示された後で初めてビューが挿入されたときに、オブザーバブル配列内のアイテムが表示されないように見えます。ngIfコンテナが非同期に破棄される
この予期しない動作を示すplunker demoを参照してください。私は、最初の例がバナナを同時に表示することを期待していますがロードされましたが表示されます。
私は何か愚かなことをしていますか、これはレンダリングのバグですか?
app.service.ts
export class AppService {
private _things = new Subject<Array<any>>();
public things = this._things.asObservable();
constructor() {
var that = this;
// simulate ajax request
setTimeout(function() {
that._things.next([
{'id': 1, 'text': 'banana'}
]);
}, 3000);
setTimeout(function() {
that._things.next([
{'id': 1, 'text': 'banana'},
{'id': 2, 'text': 'orange'}
]);
}, 6000);
setTimeout(function() {
that._things.next([
{'id': 1, 'text': 'banana'},
{'id': 2, 'text': 'orange'},
{'id': 3, 'text': 'apple'}
]);
}, 9000);
}
}
app.ts
@Component({
selector: 'my-app',
template: `
<h4>Does have *ngIf</h4>
<div *ngIf="hasThings">
Loaded
<ul>
<li *ngFor="let thing of things | async">
{{thing.id}}: {{thing.text}}
</li>
</ul>
</div>
<h4>Doesn't have *ngIf</h4>
<div>
Loaded
<ul>
<li *ngFor="let thing of things | async">
{{thing.id}}: {{thing.text}}
</li>
</ul>
</div>
`,
directives: [NgClass, NgStyle, CORE_DIRECTIVES, FORM_DIRECTIVES]
})
export class App implements OnInit {
public hasThings = false;
private _things = new Subject<Array<any>>();
public things = this._things.asObservable();
constructor(private _appService: AppService) {
}
ngOnInit() {
this._appService.things
.subscribe(things => {
this.hasThings = things.length > 0;
this._things.next(things);
});
}
}
あなたplunkが私のために働くようだ... –