ngFor不会在NavigationEnd事件Angular 6+上加载动态填充的数组



在我的类的构造函数中显示NavigationEnd事件上的ngFor数组时出现问题

testArray = [];
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
this.router.events.forEach(event => {
if (event instanceof NavigationEnd) {
this.testArray = [1, 2, 3,4];
}
});
}

<ol class="breadcrumb">
<li *ngFor="let element of testArray"
class="breadcrumb-item">
{{element}}
</li>
</ol>

即使在NavigationEnd事件发生时填充了数组,它也不会显示数组的内容。html页面似乎没有重新加载新的Array数据。如有任何帮助,我们将不胜感激。

感谢

如果在这里使用异步管道会更好

testArray: Observable<number[]>;
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
testArray = this.router.events.pipe(filter(event) => event instanceof NavigationEnd).map(() => [1, 2, 3,4])
}
<ol class="breadcrumb">
<li *ngFor="let element of testArray | async" class="breadcrumb-item">
{{element}}
</li>
</ol>

设置值时使用setTimeout

testArray = [];
constructor(private activatedRoute: ActivatedRoute,
private router: Router) {
this.router.events.forEach(event => {
if (event instanceof NavigationEnd) {
setTimeout(()=>{
this.testArray = [1, 2, 3,4];
});
}
});
}

视图似乎是在数组填充之前加载的。你可以试着让你的类实现"OnInit"从"@angular/core"中可用,并在"ngOnInit"方法上做foreach:

ngOnInit() {
this.router.events.forEach(event => {
if (event instanceof NavigationEnd) {
this.testArray = [1, 2, 3,4];
}
});
}

最新更新