[英]ngIf: async inside ngIf template
Angular:11.0.2(显示我的问题的简化示例)
我在ngIf
模板中使用async
pipe 时遇到一些问题(我的数据没有很好地刷新)。 我写了一个简单的例子来暴露我的问题。
重现步骤:
add
toggle
data$ | async
data$ | async
显示defaultValue
而不是myArray
值(不是预期的)add
data$ | async
data$ | async
被刷新并显示myArray
值(预期)toggle
data$ | async
data$ | async
再次显示defaultValue
(不是预期的) 看起来 ngIf 将 data$ 初始值存储在第一个 ngOnInit 上。 为什么{{data$ | async | json}}
{{data$ | async | json}}
{{data$ | async | json}}
在切换ngIf
块时返回myArray
的默认值(即使myArray
已更改)。
如何使用rxjs
和ngIf
处理这种情况?
模板:
<button (click)="add()">+ add</button>
<button (click)="sub()">- sub</button>
<button (click)="toggle()">toggle</button>
myArray={{myArray.value | json}}
length={{myArray.length}}
<div *ngIf="showMe">
Inside ngIf:<br>
data={{data$ | async | json}}<br>
myArray={{myArray.value | json}}
</div>
零件:
import { Component, OnInit,ChangeDetectorRef } from "@angular/core";
import { FormArray, FormBuilder } from "@angular/forms";
import { combineLatest, Observable, of } from "rxjs";
import { filter, map, startWith, tap } from 'rxjs/operators';
@Component({
selector: "my-app",
templateUrl: "src/app.component.html"
})
export class AppComponent implements OnInit{
showMe = false;
form: FormGroup;
x: number = 0;
data$: Observable<any>;
constructor(
private fb: FormBuilder,
private cd: ChangeDetectorRef
) {}
ngOnInit() {
this.form = this.fb.group({
myArray: this.fb.array(['defaultValue'])
}) ;
this.data$ = this.myArray.valueChanges.pipe(startWith(this.myArray.value));
}
add() {
this.myArray.push(this.fb.control(this.x++));
}
sub() {
this.myArray.removeAt(this.myArray.length - 1);
}
toggle() {
this.showMe = !this.showMe;
}
get myArray(): FormArray {
return this.form.get('myArray') as FormArray;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.